Vs code settings json
Vs code settings json
VS Code. How to open JSON settings with defaults
When I’m opening settings using Preferences: Open Settings (JSON) I’m getting screen like this:
But in VSCode videos/tutorials I see people somehow have splitted window, with default settings on the left and user/workspace setting on the right:
How I can enable it?
EDIT:
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
As mentioned @Juraj Kocan in comments, it happens after last VS Code updates.
This is Github issue related to this new «feature»
How to Get to the JSON settings in Newer Versions of VS Code
In the latest versions of VS Code, you can convert back to the split JSON settings editor by changing the following settings in the (now standard) UI settings editor:
Workbench > Settings: Editor
Workbench > Settings: Use Split JSON
after making this change, VS Code will open its settings as a JSON file, like in older versions of the application, rather than in the new UI. This allows you to make the changes that other answers provide, directly in the JSON (if you can find the right place and file to make them in..)
NOTE: Whether or not you actually want to use the JSON settings is a different question. Most of the time, the settings search function allows finding the same settings in the new UI. Sometimes it is difficult to get search to work though, especially if the settings are worded differently in the new UI style. There may also be cases where extensions haven’t been updated to accommodate the new UI setting style, and so there is no option but to enter the JSON directly.
Someone suggested that you open the settings.json file in vs code and add these and those properties to it. Then you will do a web search, which may lead you to this site. Today, Ourtechroom will explain in detail Where to Find Settings.json and How to Open Settings.js in vscode.
Settings.json
Settings.json is a crucial file in the vscode editor that is used to customize the user interface and functional functionality vscode reads and applies the settings and configuration from this file, which is in JSON format with key-value pairs.
If you make changes to the settings.json file, vs code may need to be restarted for the changes to take effect. These are the global settings for VS Code.
Table of Contents
These files have a JSON extension, and JSON files are commonly used to configure vscode settings since they are familiar with many languages and developers, and the JSON structure is straightforward to comprehend.
How to Open Settings.json File?
There are various ways to open the Settings.json file and we will discuss each of Them.
Method 1: Using GUI (Graphic User Interface)
The GUI version of the vscode code settings is simple to use. To utilize these settings, you don’t need any prior understanding of the JSON format.
This will open search fields.
2 Type settings.json in the search field. This will show two options. Just select Open Settings(JSON) fig. Open user settings using Shortcut and Search
This will open the settings.json file, which you may update and save to reflect your changes.
Method 2: Using GUI (Graphic User Interface)
The steps are as follows
1 Open VSCode editor
2 Click on Gear Icon located at the bottom left corner.
3 Then Click on Settings.
4 Click on File like icon located at the top right corner. fig. Open settings.json using Gear Option VSCode
This will open the settings.json file.
Method 2: Using File Explorer
The default location for user settings of vscode are as follows:
Simply navigate to these paths according to your operating system. Then, look for the settings.json file. Simply open that JSON file in any text editor and make the necessary modifications and save the file.
We discussed user settings in all three methods. settings.json, which is a global setting that applies to all of your VSCode projects.If you want project-specific or workspace configurations, please see the following:
WorkSpace Settings VS Code
Suppose you have a different project and you do not want to use all settings under settings.json then you can override this setting with WorkSpace Settings. When you want to share project-specific settings with your team, workspace settings come in handy. Workspace settings are applied to those folders and projects which are within the workspace. These settings files are located at the same level as your Projects Folder.
You can also have multiple root folders in a VS Code workspace using a feature called Multi-root workspaces.
WorkSpace Projects can be saved as your wish as you like.
Workspace Settings filename looks like this: .code-workspace and you can save it as where you like.And its settings look like this:
Open WorkSpace Setting Using GUI in vs code
Steps to open Workspace Settings using GUI are as follows:
1 First, open your desired Workspace.
2 Then Right-click on File > Preference > Settings
3 Navigate to Workspace tab
4 Then make changes on these settings that will apply to your current workspace. fig. Workspace settings
Folder Settings vs code
When you create a workspace, you will have many project folders, and each project folder can have settings.json. You can create a settings.json file inside your projects folder.
Its location will be in :
Open Folder Settings vs code
The steps are as follows:
1 First, open your desired Workspace.
2 Then Right-click on File > Preference > Settings
3 Navigate to your Project Folder tab
4 Then make changes on these settings that will apply to your current project only.
As a result, we discovered that settings in User Settings are overridden by Workspace settings, which are then overridden by Folder settings.
Conclusion:
In this way, we can open and view the different levels of settings like user settings, workspace settings, and projects settings in vscode.
Vs code settings json
Editing JSON with Visual Studio Code
IntelliSense and validation
For properties and values, both for JSON data with or without a schema, we offer up suggestions as you type with IntelliSense. You can also manually see suggestions with the Trigger Suggestions command ( kb(editor.action.triggerSuggest) ).
We also perform structural and value verification based on an associated JSON schema giving you red squiggles. To disable validation, use the json.validate.enable setting.
Package and project dependencies
JSON files can get large and we support quick navigation to properties using the Go to Symbol command ( kb(workbench.action.gotoSymbol) ).
When you hover over properties and values for JSON data with or without schema, we will provide additional context.
You can format your JSON document using kb(editor.action.formatDocument) or Format Document from the context menu.
You can fold regions of source code using the folding icons on the gutter between line numbers and line start. Folding regions are available for all object and array elements.
JSON with Comments
JSON schemas and settings
To understand the structure of JSON files, we use JSON schemas. JSON schemas describe the shape of the JSON file, as well as value sets, default values, and descriptions. The JSON support shipped with VS Code supports all draft versions from Draft 4 to JSON Schema Draft 2020-12.
Servers like JSON Schema Store provide schemas for most of the common JSON-based configuration files. However, schemas can also be defined in a file in the VS Code workspace, as well as the VS Code settings files.
Mapping in the JSON
In the following example, the JSON file specifies that its contents follow the CoffeeLint schema.
Mapping in the User Settings
Mapping to a schema in the workspace
Mapping to a schema defined in settings
Mapping a schema in an extension
Schemas and schema associations can also be defined by an extension. Check out the jsonValidation contribution point.
File match syntax
The file match syntax supports the ‘*’ wildcard. Also, you can define exclusion patterns, starting with ‘!’. For an association to match, at least one pattern needs to match and the last matching pattern must not be an exclusion pattern.
Define snippets in JSON schemas
JSON schemas describe the shape of the JSON file, as well as value sets and default values, which are used by the JSON language support to provide completion proposals. If you are a schema author and want to provide even more customized completion proposals, you can also specify snippets in the schema.
The following example shows a schema for a key binding settings file defining a snippet:
This is an example in a JSON schema:
Use the property defaultSnippets to specify any number of snippets for the given JSON object.
Note that defaultSnippets is not part of the JSON schema specification but a VS Code-specific schema extension.
Use rich formatting in hovers
VS Code will use the standard description field from the JSON Schema specification in order to provide information about properties on hover and during autocomplete.
If you want your descriptions to support formatting like links, you can opt in by using Markdown in your formatting with the markdownDescription property.
Note that markdownDescription is not part of the JSON schema specification but a VS Code-specific schema extension.
A warning triangle will show in the status bar when the current editor would like to use schemas that cannot be downloaded.
User and Workspace Settings
It’s easy to configure VS Code the way you want by editing the various setting files where you will find a great number of settings to play with.
VS Code provides two different scopes for settings:
Creating User and Workspace Settings
The menu under File > Preferences provides entries to configure user and workspace settings. You are provided with a list of Default Settings. Copy any setting that you want to change to the related settings.json file.
In the example below, we disabled line numbers in the editor and configured line wrapping to wrap automatically based on the size of the editor.
Changes to settings are reloaded by VS Code after the modified settings.json file is saved.
Settings File Locations
Depending on your platform, the user settings file is located here:
Settings File Sections
The settings.json file is divided into these sections:
Default Settings
Below is a copy of the default settings.json file.
Tip: While in the settings.json file, press kb(workbench.action.gotoSymbol) to see an outline of all available settings and navigate through the file.
Common Questions
Q: When does it make sense to use workspace settings?
A: If you’re using a workspace that needs custom settings but you don’t want to apply them to your other VS Code projects. A good example is language-specific linting rules.
Areg Sarkissian
September 28, 2020 by Areg Sarkissian
In this post I will describe how I customize and use the Visual Studio Code (VSCode) editor for a more productive development experience.
Most of my setup is based on excellent resources by others on this topic. I will provide links to those resources at the end of this post.
Before I go through my setup, it will help to detail how VSCode settings and keyboard shortcuts are configured, which I will describe in the following sections.
VSCode settings files
The default VSCode settings are listed in a defaultSetttings.json file. This file is readonly and can not be directly modified.
The settings in the defaultSetttings.json file can be overridden by user settings in a settings.json file. This is a VSCode User settings file that is located at
/Library/Application Support/Code/User/settings.json on my MacBook.
On a Mac, all VSCode user configuration files are located in the
/Library/Application Support/Code/User/ directory.
To override a setting from the defaultSetttings.json file, all we need to do is manually copy that setting into our settings.json file and set its value to what we want.
Also, when we change settings using the VSCode menu, VSCode adds the setting we changed to the settings.json file with the changed value. After that, any time we update the setting using the VSCode menu, VSCode will update the value of the setting in the settings.json file. Conversely, opening up the settings.json file and updating a setting manually, will get reflected in the VSCode menu.
There can also be a per workspace directory settings.json file that can override both the Global (defaultSettings.json) and User (settings.json) file settings.
A workspace is the root directory in the VSCode explorer which is the directory from which VSCode is launched. For example if we cd into a directory named
VSCode keyboard shortcut settings files
The VSCode keyboard shortcut settings work in a similar way as the VSCode editor settings.
There is a global defaultKeyboardSettings.json file located in the VSCode installation location that is readonly. There is a user keyboardSettings.json file located at
There is no per workspace keyboard shortcut settings file.
Accessing the JSON settings files
Now that we know how to configure settings using the VSCode JSON settings files, I will describe how to access those files to make your changes.
To open the JSON settings files use the cmd+sh+p keyboard shortcut to open the global command palette dropdown and type the word settings in the search box. This will show options for selecting settings files that have the text (JSON) in their description.
Select the defaultSetttings.json or setttings.json option to open the respective settings file. Use the defaultSetttings.json file settings as a reference to copy settings you want to modify to the setttings.json file.
Similarly, to open the keyboard shortcut settings files, type the word keyboard in the global command palette. This will show options for selecting keyboard settings files, that have the text (JSON) in their description.
Select the defaultKeyboardSetttings.json or keyboardSetttings.json option to open the respective settings file. Use the defaultKeyboardSetttings.json file settings as a reference to copy settings you want to modify to the keyboardSetttings.json file.
Steps to setup my VSCode preferences
In each of the following sections I show how I customize a particular section of the editor
Moving search results panel from side panel to bottom panel
The first thing I do after installing VSCode is move the location of the search results panel from the side panel to the bottom panel.
Unfortunately there is no settings option to change the location so we must resort to dragging the search icon from the side panel activity bar to the bottom panel tab area.
If the bottom panel is not visible select cmd+j keyboard shortcut to open it.
After moving the search panel to the bottom panel, set its tab position in the bottom panel tab area by sliding the search tab to your desired position.
Note: There may be a search.location setting in the defaultSetttings.json but it is deprecated and the related comments in the settings file suggest using drag and drop to change the file search panel location.
Moving and hiding file explorer side panel sections
Open the file explorer side panel using the file explorer activity bar icon or by pressing the cmd+sh+e keyboard shortcut.
Collapse all the sections in the explorer side panel.
Drag the open editors section, in the file explorer side panel, down to the last position at the bottom. This way the files section will become the topmost section in the file explorer side panel.
Now whenever the open editors section is open, it won’t move the files section that used to be located below it, up and down as you open and close files or as you collapse/expand the open editors section.
After this I actually like to hide all the sections except the files and timelines sections.
To do that, right click anywhere in file explorer panel or click on the dropdown menu button in the upper right corner of the file explorer panel to bring up menu options for hiding and showing the panel sections.
Hiding the status and activity bars
Right click on status bar to popup a context menu that will allow you to hide the status bar. Alternatively select view > appearance > show status bar to uncheck the status bar menu item.
Right click on activity bar to popup a context menu that will allow you to hide the activity bar. Alternatively select view > appearance > show activity bar to uncheck the activity bar menu item.
Note: By hiding the activity bar, you will be forced to use the VSCOde view menu or keyboard shortcuts to open the side panels. See the section Shortcuts for opening\closing activity side panels below for the keyboard shortcuts to open, close and toggle commonly used side panels.
Overriding VSCode default settings
To override the VSCode default settings, I select cmd+sh+p keys then type in the text settings in the search box. This brings up the Preferreces: Open Settings (JSON) selection, which I select to open the user
/Library/Application Support/Code/User/settings.json file.
Then I add the following override settings to the settings.json file:
Overriding VSCode default keyboard shortcuts
To override the VSCode default settings, you can select cmd+sh+p keyboard shortcut and then type in the text keyboard in the search box. This brings up the Preferreces: Open Keyboard shortcuts (JSON) selection, which you can select to open the user
/Library/Application Support/Code/User/keyboardSettings.json file.
You can configure keyboard shortcuts by adding settings to the keyboardSettings.json file to override the default VSCode settings in the defaultKeyboardSettings.json file.
Commonly used keyboard shortcuts
For everyday use, the keyboard shortcuts listed in the following sections can boost your productivity.
Shortcuts for opening\closing activity side panels
Open\Close toggle last selected side panel cmd+b
Open file explorer panel / toggle focus when panel is open (closes the current open panel) cmd+sh+e (use cmd+b to close panel)
Open debugger panel / toggle focus when panel is open (closes the current open panel) cmd+sh+d (use cmd+b to close panel)
Open git panel / toggle focus when panel is open (closes the current open panel) ctrl+sh+g (use cmd+b to close panel)
Open extensions panel / toggle focus when panel is open (closes the current open panel) cmd+sh+x (use cmd+b to close panel)
Shortcuts for opening\closing bottom panels
Open\Close toggle current tab of bottom panel cmd+j
Open\Close toggle terminal tab in bottom panel ‘ctrl+`’ (ctrl+backtick)
Open search in files tab in bottom panel cmd+sh+f (use cmd+j to close panel)
Note: The ‘search in files’ panel tab was dragged from its default side panel location to the bottom panel
Shortcuts for navigation drop downs
Open ‘search for files’ by name dropdown cmd+p
Open ‘Command Palette’ dropdown cmd+sh+p
Other useful shortcuts
toggle comment line(s)
Find in current File
close current file
Save current file
Save all modified files
Open VSCode configuration settings UI
Close various panels
Editing with multiple cursors
Hold the option key down and click the mouse cursor two or more locations to spawn multiple persistent cursors at those locations. Then release the option key.
Then when you type characters, they will appear at all cursor locations.
Hit escape or click anywhere to change to single cursor at that location.
Vs code settings json
User and Workspace Settings
It is easy to configure VS Code to your liking through settings. Nearly every part of VS Code’s editor, user interface, and functional behavior have options you can modify.
VS Code provides two different scopes for settings:
Creating User and Workspace Settings
The menu command File > Preferences > Settings (Code > Preferences > Settings on Mac) provides entry to configure user and workspace settings. You are provided with a list of Default Settings. Copy any setting that you want to change to the appropriate settings.json file. The tabs on the right let you switch quickly between the user and workspace settings files.
You can also open the user and workspace settings from the Command Palette ( kb(workbench.action.showCommands) ) with Preferences: Open User Settings and Preferences: Open Workspace Settings.
In the example below, we disabled line numbers in the editor and configured line wrapping to wrap automatically based on the size of the editor.
Changes to settings are reloaded by VS Code after the modified settings.json file is saved.
Note: Workspace settings are useful for sharing project specific settings across a team.
Settings File Locations
Depending on your platform, the user settings file is located here:
When you open settings, we show Default Settings to search and discover settings you are looking for. When you search using the big Search bar, it will not only show and highlight the settings matching your criteria, but also filter out those which are not matching. This makes finding settings quick and easy. There are actions available inside Default Settings and settings.json editors which will help you quickly copy or update a setting.
Note: VS Code extensions can also add their own custom settings and they will be visible in the Default Settings list at runtime.
Default settings are represented in groups so that you can navigate them easily. It has Most Commonly Used group on the top to see the most common customizations done by VS Code users.
Here is the copy of default settings that comes with VS Code.
Language specific editor settings
To customize your editor by language, run the global command Preferences: Configure language specific settings. (command id: workbench.action.configureLanguageBasedSettings ) from the Command Palette ( kb(workbench.action.showCommands) ) which opens the language picker. Selecting the language you want, opens the Settings editor with the language entry where you can add applicable settings.
You can use IntelliSense in Settings editor to help you find allowed language based settings. All editor settings and some non-editor settings are supported.
Settings and security
In settings, we allow you to specify some of the executables that VS Code will run to do its work. For example, you can choose which shell the Integrated Terminal should use. For enhanced security, such settings can only be defined in user settings and not at workspace scope.
Here is the list of settings we don’t support at the workspace scope:
The first time you open a workspace which defines any of these settings, VS Code will warn you and subsequently always ignore the values after that.
Copy of Default Settings
Below are the default settings and their values.
Q: When does it make sense to use workspace settings?
A: If you’re using a workspace that needs custom settings but you don’t want to apply them to your other VS Code projects. A good example is language-specific linting rules.
Customizing default settings
Visual Studio Code settings
These settings have all of the benefits of VS Code settings, meaning that they can have default, «User», «Workspace», and «Folder» values. So you can set a global value for C_Cpp.default.cppStandard in your «User» settings and have it apply to all of the folders you open. If any one folder needs a different value, you can override the value by adding a «Folder» or «Workspace» value.
Updated c_cpp_properties.json syntax
A special variable has been added to the accepted syntax of c_cpp_properties.json that will instruct the extension to insert the value from the VS Code settings mentioned above. If you set the value of any setting in c_cpp_properties.json to «$
For in-depth information about the c_cpp_properties.json settings file, See c_cpp_properties.json reference.
System includes
A new setting will be added that allows you specify the system include path separate from the folder’s include path. If this setting has a value, then the system include path the extension gets from the compiler specified in the compilerPath setting will not be added to the path array that the extension uses for IntelliSense. We may want to provide a VS Code command to populate this value from the compiler’s default for users who are interested in using it in case they want to make some modifications to the defaults.
System include path/defines resolution strategies
The extension determines the system includePath and defines to send to the IntelliSense engine in the following manner:
If compileCommands has a valid value and the file open in the editor is in the database, use the compile command in the database entry to determine the include path and defines.
If compileCommands is invalid or the current file is not listed in the database, use the includePath and defines properties in the configuration for IntelliSense.
System includes should not be added to the includePath or browse.path variables. If the extension detects any system include paths in the includePath property it will silently remove them so that it can ensure system include paths are added last and in the correct order (this is especially important for GCC/Clang).
Enhanced semantic colorization
When IntelliSense is enabled, the Visual Studio Code C/C++ extension supports semantic colorization. See Enhanced colorization for more details about setting colors for classes, functions, variables and so on.
Extension logging
If you are experiencing a problem with the extension that we can’t diagnose based on information in your issue report, we might ask you to enable logging and send us your logs. See C/C++ extension logging for information about how to collect logs.
Editing JSON with Visual Studio Code
IntelliSense and validation
For properties and values, both for JSON data with or without a schema, we offer up suggestions as you type with IntelliSense. You can also manually see suggestions with the Trigger Suggestions command ( ⌃Space (Windows, Linux Ctrl+Space ) ).
We also perform structural and value verification based on an associated JSON schema giving you red squiggles. To disable validation, use the json.validate.enable setting.
Package and project dependencies
Quick navigation
JSON files can get large and we support quick navigation to properties using the Go to Symbol command ( ⇧⌘O (Windows, Linux Ctrl+Shift+O ) ).
Hovers
When you hover over properties and values for JSON data with or without schema, we will provide additional context.
Formatting
Folding
You can fold regions of source code using the folding icons on the gutter between line numbers and line start. Folding regions are available for all object and array elements.
JSON with Comments
JSON schemas and settings
To understand the structure of JSON files, we use JSON schemas. JSON schemas describe the shape of the JSON file, as well as value sets, default values, and descriptions. The JSON support shipped with VS Code supports all draft versions from Draft 4 to JSON Schema Draft 2020-12.
Servers like JSON Schema Store provide schemas for most of the common JSON-based configuration files. However, schemas can also be defined in a file in the VS Code workspace, as well as the VS Code settings files.
Mapping in the JSON
In the following example, the JSON file specifies that its contents follow the CoffeeLint schema.
Mapping in the User Settings
Mapping to a schema in the workspace
Mapping to a schema defined in settings
Mapping a schema in an extension
Schemas and schema associations can also be defined by an extension. Check out the jsonValidation contribution point.
File match syntax
The file match syntax supports the ‘*’ wildcard. Also, you can define exclusion patterns, starting with ‘!’. For an association to match, at least one pattern needs to match and the last matching pattern must not be an exclusion pattern.
Define snippets in JSON schemas
JSON schemas describe the shape of the JSON file, as well as value sets and default values, which are used by the JSON language support to provide completion proposals. If you are a schema author and want to provide even more customized completion proposals, you can also specify snippets in the schema.
The following example shows a schema for a key binding settings file defining a snippet:
This is an example in a JSON schema:
Use the property defaultSnippets to specify any number of snippets for the given JSON object.
Note that defaultSnippets is not part of the JSON schema specification but a VS Code-specific schema extension.
Use rich formatting in hovers
VS Code will use the standard description field from the JSON Schema specification in order to provide information about properties on hover and during autocomplete.
If you want your descriptions to support formatting like links, you can opt in by using Markdown in your formatting with the markdownDescription property.
Note that markdownDescription is not part of the JSON schema specification but a VS Code-specific schema extension.
Offline mode
A warning triangle will show in the status bar when the current editor would like to use schemas that cannot be downloaded.
Cannot change visual studio code settings
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
These are the steps I used: 1. Ctrl-Shift-p to open the Command palette
2. Search for Settings and click Preferences: Open User Settings
3. In the left hand pane, click on the setting you want to change
4. Click on the pencil icon to the left of the setting. It will either give you the valid options from which to choose or it will let you copy the option to user settings.
The answers here are good examples of ‘partial answers and also of ‘insufficient answers’.
While each contains one or more facts that are members of the context information of the problem/solution space, each lacks any feature that would relieve the ambiguity of the problem space.
What is necessary is evidence that these facts can be utilized successfully. To wit: two columns do seem to open up, the left showing the json settings objects, the right showing the statement, «place your settings here to overwrite the default settings.»
To perform this operation, you may need to right click your VS Code icon on your windows task-bar and choose properties/advanced and set the permanent option to ‘run as administrator’
At that point, you can use the pencil icon to copy a ‘default settings/value pair’ to the right-hand list, which is the only editable list. If you do not migrate a setting/value pair to the right hand list by means of the pencil icon, or by manually entering the settings/value pair into the right hand list, then the pencil icon will appear to do nothing.
After migrating the setting, you will have to edit it to meet your needs. If you later discover that your self-defined settings are inappropriate, you should edit them from the right-hand list only, and then reload to save your edits.
If you try to use the pencil icon on the left hand list to enter an editing session for the values on the left hand list, you will be sorry, the pencil icon only serves one purpose: to migrate the default value to the right hand list.
So if you click the pencil icon, any custom values you have entered will be replaced by the default value. The pencil icon cannot be used to ‘edit’ a value in the right hand list, despite the ‘edit’ tool tip it displays on hover.
The only relationship the pencil has to ‘editing’ is to save you the trouble of manually entering a default settings/key value into the single object brace pair on the right hand side. (unless you consider its ability to whack your manual changes and replace them with the default values as ‘editing’)
That’s how it works:
you must start by placing a settings/value from the left hand list of defaults into the single object brackets on the right by using the pencil icon, or by entering the settings/value pair by hand. If you choose to enter the values into right hand list by hand (per the ‘placing’ instructions), then do not use the pencil icon (unless you want to restore the default values).
You must use Ctrl-Shift-p, and select to reload the window in order to successfully save and apply your new settings.
If you do not like your new/changed settings AND you want to restore the defaults, click the pencil on the left for the settings/value pair you want to change. This will replace your settings/value pair on the right hand side with the default values (only) so save your original changes somewhere if you want to be able to get those back.
If you want to edit your changed settings to new changed settings, DO NOT use the pencil icon, but re-edit your settings in the right hand column. (and reload)
Oct 11, 2018: Hmm, I thought I explained this to a level of detail that was sufficient to address the level of confusion that VS Code designers had created by providing this backwards-mirror and insanely convoluted editing process.
I still think the details I provided are the fundamental understanding needed to ‘feel your way’ through this process, even though its been a year and the designers have added a number of features to this config-file-editor-for-martians.
Cannot Edit Default VSCode JSON Settings
I am using VSCode 1.47.3 on Windows 10. I cannot edit default settings in json:
I’ve tried opening VSCode as admin, uninstalling and reinstalling, restarting my computer, and downgrading to 1.46, but still cannot edit. Does someone know how to fix this?
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The default settings in vscode is a non-editable document. It acts as a way for you to view the default settings for native settings as well as extension default settings.
These defaults are also used to identify when a setting has changed with a ‘blue’ line indicator, when using the settings editor:
Changes to settings are reloaded by VS Code as you change them. Modified settings are now indicated with a blue line similar to modified lines in the editor. The gear icon opens a context menu with options to reset the setting to its default value as well as copy setting as JSON.
Currently, vscode only offers 2 editable settings:
VS Code provides two different scopes for settings:
Workspace settings override user settings. Workspace settings are specific to a project and can be shared across developers on a project.
You can configure these settings with the settings editor, as pictured above, or you can navigate to their JSON counterparts for manual entry (example pictured on the right below).
By default, VS Code shows the Settings editor, but you can still edit the underlying settings.json file by using the Open Settings (JSON) command from your command palette or by changing your default settings editor with the workbench.settings.editor setting.
Settings
You can define which view is shown using the following settings:
Opens the default settings any time you open regular settings (this only works with the JSON settings editor option)
Determine which editor to use, you can elect UI or JSON
What are ALL configuration files used by Visual Studio Code?
I’m wondering if there’s also another place.
For example, if you create a file without using New File button, e.g. from terminal:
And then you open it in the editor, you will be prompted with a dialog like this:
If you hit Don’t Show Again. and repeat the same experiment in the same directory or in another, VS Code will remember it (it will not present the dialog a second time).
I know it’s not an important thing. But I want to know where this is stored.
So, are there any other config file that VS Code uses?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You can access your defaultSettings.json by typing «default settings» in the command palette ( Shift + Cmd + P or Shift + Ctrl + P in Windows/Linux).
You can access your user settings.json file by pressing Cmd+, (or Ctrl+, in Windows/Linux).
The single-folder settings go into the /.vscode/settings.json file. The single-folder state is a legacy feature. You can insert both repository-wide and workspace-wide settings inside the /.vscode/settings.json file when in a single-folder state but workspace settings stop working if you turn that into a workspace. This can be confusing because VS Code creates an implicit/unsaved workspace if you choose the » Remove folder from Workspace » or the » Add folder to workspace » options in your file explorer.
The repository settings go into the /.vscode/settings.json file.
I’ve recorded a video on where settings are applied that contains a slight misconception, which I’m hoping to correct soon, around the single-folder legacy functionality that I was not aware of at the time of the recording. I hope this helps 🙂
Depending on your platform, the user settings file is located here:
If you take a look at the Code folder, there are a bunch of other files stored there:
Those contain all the settings/configurations that VS Code maintains (apart from the .vscode folder in your workspace). If you delete the Code folder, your VS Code would then behave like it was freshly installed.
Most of them aren’t easily readable like JSON though, and most are stored in SQL DB files (.vscdb). For example, for remembering that «Don’t Show Again» prompt for files with .abc extensions, it’s stored in User/globalStorage/state.vscdb. Use a SQLite browser (like this) to open up that file, and you’ll see this:
. which stores the setting to not prompt me again for .csv and .abc files. (Try removing the «abc» from the DB value, and VS Code will prompt you again.)
For workspace-specific settings, they are stored in User/workspaceStorage, where each workspace is organized into folders like this:
Go into any one, and check the workspace.json to know which workspace the DB file is for. Then again open the state.vscdb to see something like this:
. which shows settings for remembering which files are opened, etc..
How to change visual studio code settings
I am trying to changes visual studio code settings.json but it is not working. I have updated this in C:\Users\Userid\AppData\Roaming\Code\User\settings.json but not working. How to edit settings.json file in vs code?
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
VSCode’s settings are split into 2 categories: User and Workspace.
User settings
Settings that apply globally to any instance of VS Code you open.
VSCode settings pane with User Settings tab open
Editing JSON schemas
The VSCode settings page does not allow direct editing of JSON Schemas. To edit JSON schema settings: 1. Search JSON schemas in the VSCode settings page 2. Click «edit in settings.json» 3. Edit settings 4. Done!
JSON schema setting in VSCode
Workspace settings
Settings stored inside your workspace and only apply when the workspace is opened.
Workspace settings override user settings.
To edit workspace settings, follow steps for user settings, except click the Workspace Settings tab instead. Note that workspace settings will override user settings
VSCode Settings.json is missing
I’m following a tutorial and I’m trying to point vscode to my virtual workspace I had set up for Scrapy, but when I open settings in VSCode, Workspace Settings tab is not there next to User Settings tab. Also I tried to go to file manually by going to %APPDATA%\Code\User\settings.json which I got from here: https://vscode.readthedocs.io/en/latest/getstarted/settings/ but settings.json isn’t in there. How can I get this setting to appear or get to my settings.json file so I can make the necessary edits. Any help is appreciated.
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You should use the official documentation for this sort of thing as it’s up to date, the readthedocs version appears to be an out of date rip of the website from the past.
You can access the actual file by clicking the button with the file icon in the top-right:
How do I update my config file in vs code?
When I see example config files on VS Code they are often lengthy and offer two panels for updating (one for default settings and the other for customization). For some reason my config file is only a few lines and whenever I try to update it, nothing happens:
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
All these you can find in UI instead of JSON.
In your example, you provided Launch configuration (it is not vs code settings), it is used to configure how to launch/debug your application.
And if you want to get rid of errors, you don’t need to use VS Code settings. These rules:
What is the location of the default settings file of VSCode?
There is a storage.json in the %AppData%\Code\User\ but that doesn’t look like the whole settings.
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
As @Scott McPeak pointed out the defaults are not stored, however if you override any value the overrides are stored on a *nix system in:
you can find the default settings for user C:\Users\yourusername\AppData\Roaming\Code\User
The list of default settings is not stored in a single file: it is generated when you ask for it.
(It makes sense to generate it every time the user asks for it because it might have changed since the last time the user asked for it because an extension might have been installed or uninstalled: the list includes settings specific to an extension.)
It might be that your reason for asking is because you want a way to view the list without splitting the editor. (That was my reason for doing the web search that led me to this page.) That can be achieved by running the command «Preferences: Open Default Settings (JSON)».
All defaults in a read-only format
If you just want to see what all the defaults are, use the Command Palette (Ctrl+Shift+P) and run «Preferences: Open Default Settings (JSON)». VSCode will generate a JSON description of all of the defaults.
Where the defaults come from
The default settings are hardcoded in the vscode sources.
Details
Let’s look at some examples. When I open Settings, I see a long list, and this is at the top:
The first entry is «Files: Auto Save». That is defined by this fragment of Typescript code in files.contribution.ts:
Notice the default value, which incidentally depends on the isWeb variable. Since I’m running VSCode on Windows (where isWeb is evidently false), I see a default value of «off» for this attribute.
The next attribute is «Files: Auto Save Delay». As it happens, the very next fragment in the same file contains it:
Again, the default value of 1000 in the GUI comes from the default attribute here.
The next attribute is «Editor: Font Size». It comes from commonEditorConfig.ts:
It is again interesting that the default depends on the platform. Since I’m not running on Mac, I see a default of 14.
Vs code settings json
В этом посте я постараюсь вам рассказать о самых простых и необходимых настройках редактора VS Code, для облегчения работы в нем и как пример приведу мои настройки редактора.
Расширения:
Как правило, о назначении того или иного расширения, можно догадаться из его названия. Если, нет, то пройдите по ссылке и посмотрите в описании.
В интернете очень много статей посвященных настройке этого редактора. Предлагается масса расширений, но я думаю, что это зависит от текущих задач и предпочтений пользователя.
Настройки settings.json
Еще один простой способ найти этот файл это в открытом редакторе VS Code пройти по пути :
откроется часть кода из этого файла, но зато вы сможете легко узнать к нему путь
Вы можете изменить настройки на те, которые вам нравятся, благо, что в интернете масса примеров. Там же вы можете найти настройки этого файла по умолчанию.
Но это уже другая история.
воскресенье, 14 июня 2020 г.
Кастомизация темы VSCode.
Кастомизация — индивидуализация продукции под заказы конкретных потребителей путём внесения конструктивных или дизайнерских изменений.
Сегодня я хочу вам рассказать об очень простой штуке, которая во многом, я уверен, облегчит жизнь всем тем, кто работает в редакторе VSCode. Речь пойдет о некоторых возможностях кастомизировать (настроить для ваших нужд и вкусов) тему самого редактора.
«Window: Title Bar Style
Вы можете настроить внешний вид заголовка окна. В Linux и Windows этот параметр также влияет на внешний вид меню приложения и контекстного меню. Для применения изменений требуется полная перезагрузка.»
Не забывайте добавить запятую, перед вставкой вашего куска кода!
Как вы можете легко понять из названий свойств, то мы поменяли только верхнюю панель (title).
Если вы хотите внести дополнительные изменения в саму тему именно этого проекта, то можете добавить еще некоторые настройки. Например:
Общий вид темы будет таким:
Вы можете поиграться с цветами фона основной области, боковой панели и вообще лучше разобраться в том, что за что отвечает, хотя это понятно из названий свойств, но иногда хочется добавить новых красок в проект, чтобы работать над ним было легко и приятно.
Cannot Edit Default VSCode JSON Settings
I am using VSCode 1.47.3 on Windows 10. I cannot edit default settings in json:
I’ve tried opening VSCode as admin, uninstalling and reinstalling, restarting my computer, and downgrading to 1.46, but still cannot edit. Does someone know how to fix this?
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The default settings in vscode is a non-editable document. It acts as a way for you to view the default settings for native settings as well as extension default settings.
These defaults are also used to identify when a setting has changed with a ‘blue’ line indicator, when using the settings editor:
Changes to settings are reloaded by VS Code as you change them. Modified settings are now indicated with a blue line similar to modified lines in the editor. The gear icon opens a context menu with options to reset the setting to its default value as well as copy setting as JSON.
Currently, vscode only offers 2 editable settings:
VS Code provides two different scopes for settings:
Workspace settings override user settings. Workspace settings are specific to a project and can be shared across developers on a project.
You can configure these settings with the settings editor, as pictured above, or you can navigate to their JSON counterparts for manual entry (example pictured on the right below).
By default, VS Code shows the Settings editor, but you can still edit the underlying settings.json file by using the Open Settings (JSON) command from your command palette or by changing your default settings editor with the workbench.settings.editor setting.
Settings
You can define which view is shown using the following settings:
Opens the default settings any time you open regular settings (this only works with the JSON settings editor option)
Determine which editor to use, you can elect UI or JSON
jsconfig.json
What is jsconfig.json?
The presence of jsconfig.json file in a directory indicates that the directory is the root of a JavaScript Project. The jsconfig.json file specifies the root files and the options for the features provided by the JavaScript language service.
Why do I need a jsconfig.json file?
Visual Studio Code’s JavaScript support can run in two different modes:
The JavaScript experience is improved when you have a jsconfig.json file in your workspace that defines the project context. For this reason, we offer a hint to create a jsconfig.json file when you open a JavaScript file in a fresh workspace.
Location of jsconfig.json
We define this part of our code, the client side of our website, as a JavaScript project by creating a jsconfig.json file. Place the file at the root of your JavaScript code as shown below.
In more complex projects, you may have more than one jsconfig.json file defined inside a workspace. You will want to do this so that the code in one project is not suggested as IntelliSense to code in another project. Illustrated below is a project with a client and server folder, showing two separate JavaScript projects.
Examples
By default the JavaScript language service will analyze and provide IntelliSense for all files in your JavaScript project. You will want to specify which files to exclude or include in order to provide the proper IntelliSense.
Using the «exclude» property
The exclude attribute (a glob pattern) tells the language service what files are not part of your source code. This keeps performance at a high level. If IntelliSense is slow, add folders to your exclude list (VS Code will prompt you to do this if it detects the slow down).
Tip: You will want to exclude files generated by a build process (for example, a dist directory). These files will cause suggestions to show up twice and will slow down IntelliSense.
Using the «include» property
Alternatively, you can explicitly set the files in your project using the include attribute (a glob pattern). If no include attribute is present, then this defaults to including all files in the containing directory and subdirectories. When a include attribute is specified, only those files are included. Here is an example with an explicit include attribute.
jsconfig Options
Below are jsconfig «compilerOptions» to configure the JavaScript language support.
Option | Description |
---|---|
noLib | Do not include the default library file (lib.d.ts) |
target | Specifies which default library (lib.d.ts) to use. The values are «es3», «es5», «es6», «es2015», «es2016», «es2017», «es2018», «es2019», «es2020», «esnext». |
module | Specifies the module system, when generating module code. The values are «amd», «commonJS», «es2015», «es6», «esnext», «none», «system», «umd». |
moduleResolution | Specifies how modules are resolved for imports. The values are «node» and «classic». |
checkJs | Enable type checking on JavaScript files. |
experimentalDecorators | Enables experimental support for proposed ES decorators. |
allowSyntheticDefaultImports | Allow default imports from modules with no default export. This does not affect code emit, just type checking. |
baseUrl | Base directory to resolve non-relative module names. |
paths | Specify path mapping to be computed relative to baseUrl option. |
You can read more about the available compilerOptions in the TypeScript compilerOptions documentation.
Using webpack aliases
For IntelliSense to work with webpack aliases, you need to specify the paths keys with a glob pattern.
For example, for alias ‘ClientApp’:
and then to use the alias
Best Practices
Whenever possible, you should exclude folders with JavaScript files that are not part of the source code for your project.
Tip: If you do not have a jsconfig.json in your workspace, VS Code will by default exclude the node_modules folder.
Below is a table, mapping common project components to their installation folders that are recommended to exclude:
alefragnani/vscode-settings
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
My personal Visual Studio Code settings.
I’m keeping it here because I want to have it synced between different machines.
Preferences / User Settings
Preferences / Keyboards Shortcuts
Mostly to use the same shortcut for every code editor
Preferences / User Snippets
Syncing (using Symlink)
The symlinks must be hard links, otherwise VS Code will display errors about to many link loop or something like that.
Настройка задач сборки и отладки для режима разработки «Открытая папка»
Visual Studio поддерживает множество разных языков и баз кода, но не все существующие варианты. Если вы откроете в Visual Studio папку с кодом, который поддерживает Visual Studio, его можно выполнить немедленно и без дополнительных настроек.
Если в базе кода используются пользовательские средства сборки, которые не распознаются Visual Studio, для выполнения и отладки такого кода в Visual Studio требуются определенные сведения о конфигурации. Чтобы указать Visual Studio правила сборки вашего кода, определите задачи сборки. Создав одну или несколько задач сборки, вы сможете указать в них все элементы, которые потребуются для сборки и выполнения кода на определенном языке. Кроме того, можно создавать произвольные задачи с практически неограниченными возможностями. Например, с помощью задач можно вывести список содержимого папки или переименовать файл.
Чтобы настроить базу кода, не относящуюся к конкретному проекту, воспользуйтесь следующими файлами .json:
Имя файла | Цель |
---|---|
tasks.vs.json | Определяет настраиваемые команды сборки и параметры компилятора, а также произвольные (не имеющие отношения к сборке) задачи. Доступ к файлу можно получить в обозревателе решений, выбрав пункт контекстного меню Настройка задач. |
launch.vs.json | Определяет аргументы командной строки для отладки. Доступ к файлу можно получить в обозревателе решений, выбрав пункт контекстного меню Параметры отладки и запуска. |
Описанные файлы .json находятся в скрытой папке с именем .vs в корневой папке базы кода. Файлы tasks.vs.json и launch.vs.json создаются в среде Visual Studio по мере необходимости, то есть когда вы выбираете в обозревателе решений действия Настройка задач или Параметры отладки и запуска для файла или папки. Эти файлы .json скрыты, потому что пользователи обычно не добавляют их в систему управления версиями. Но если требуется возможность записать их в систему управления версиями, с помощью файловой системы перетащите файлы в корневую папку базы кода, где они будут видны в Обозревателе решений и в системе управления версиями.
Чтобы просмотреть скрытые папки в Visual Studio, нажмите кнопку Показать все файлы на панели инструментов обозревателя решений.
Определение задач в файле tasks.vs.json
Вы можете автоматизировать скрипты сборки и любые внешние операции с файлами, размещенными в текущей рабочей области, запуская их как задачи в интегрированной среде разработки. Чтобы настроить новую задачу, щелкните правой кнопкой мыши нужный файл или папку и выберите Настройка задач.
В среде разработки откроется (или будет создан, если его еще нет) файл tasks.vs.json в папке .vs. Можно определить в этом файле задачу сборки или произвольную задачу, а затем вызывать ее по имени в контекстном меню обозревателя решений.
Настраиваемые задачи можно размещать в отдельных файлах или во всех файлах определенного типа. Например, можно определить во всех файлах пакета NuGet задачу «Восстановить пакеты» или поместить во все файлы исходного кода задачу статического анализа, например анализатор кода для всех JS-файлов.
Определение настраиваемых задач сборки
Если в базе кода используются настраиваемые средства сборки, которые не распознаются в Visual Studio, вам не удастся выполнить и отладить код в Visual Studio без нескольких дополнительных настроек. Visual Studio поддерживает задачи сборки, в которых вы можете указать Visual Studio правила сборки, перестроения и очистки кода. Файл задачи сборки tasks.vs.json связывает внутренний цикл разработки Visual Studio с пользовательскими средствами сборки, применяемыми для базы кода.
Давайте рассмотрим пример базы кода, которая состоит из одного файла на языке C# с именем hello.cs. Файл makefile для такой базы кода может выглядеть следующим образом:
Этот файл makefile содержит целевые объекты сборки, очистки и перестроения, и вы можете определить для него указанный ниже файл tasks.vs.json. Он содержит три задачи сборки (для сборки, перестроения и очистки), для которых применяется средство сборки NMAKE.
Когда вы определите в файле tasks.vs.json задачи сборки, в контекстном меню обозревателя решений для соответствующих файлов появятся дополнительные пункты. В нашем примере для всех файлов makefile в контекстное меню добавляются действия «Сборка», «Перестроить» и «Очистить».
Если вы выберете любой из этих вариантов, будет выполнена соответствующая задача. Выходные данные отображаются в окне Вывод, а ошибки сборки — в окне Список ошибок.
Определение произвольных задач
Вы можете описать в файле tasks.vs.json произвольную задачу, которая предназначена для выполнения любого действия. Например, можно определить задачу для отображения имени файла, выбранного в окне вывода, или списка файлов в указанном каталоге.
Ниже представлен пример файла tasks.vs.json, который определяет одну задачу. При вызове этой задачи отображается имя выбранного файла .js.
Сохранив файл tasks.vs.json, вы можете щелкнуть правой кнопкой мыши любой файл .js и выбрать команду Echo filename (Отобразить имя файла). Имя файла будет отображено в окне Вывод.
Если в базе кода нет файлов tasks.vs.json, вы можете создать такой файл с помощью команды Настройка задач в контекстном меню обозревателя решений. Эту команду также можно вызвать, щелкнув файл правой кнопки мыши.
В следующем примере определяется задача перечисления всех файлов и вложенных папок из каталога bin.
Эта задача применяется ко всем файлам. Открыв в обозревателе решений контекстное меню для любого файла, вы увидите в нижней части этого меню задачу с именем List Outputs (Перечислить выходные объекты). Если выбрать команду List Outputs (Перечислить выходные объекты), все содержимое каталога bin выводится в окне Вывод в Visual Studio.
Область действия параметров
В корневой папке и вложенных папках базы кода может быть несколько файлов tasks.vs.json. Такой подход позволяет гибко настраивать разные правила для разных каталогов в базе кода. Visual Studio объединяет или переопределяет параметры для разных разделов базы кода, используя следующий приоритет файлов:
Эти правила агрегирования применяются к tasks.vs.json. Сведения о правилах агрегирования параметров для другого файла см. в посвященном ему разделе этой статьи.
Свойства для tasks.vs.json
В этом разделе описаны некоторые свойства, которые можно задать в файле tasks.vs.json.
appliesTo
Маска файла | Описание |
---|---|
«*» | Задача доступна для всех файлов и папок в рабочей области. |
«*/» | Задача доступна для всех папок в рабочей области. |
«*.js» | Задача доступна для всех файлов с расширением JS в рабочей области. |
«/*.js» | Задача доступна для всех файлов с расширением JS в корневой папке рабочей области. |
«src/*/» | Задача доступна для всех подпапок в папке SRC. |
«makefile» | Задача доступна для всех файлов makefile в рабочей области. |
«/makefile» | Задача доступна только для файлов makefile в корневой папке рабочей области. |
Макросы для tasks.vs.json
Настройка отладки с помощью launch.vs.json
Сведения о настройке проектов CMake для отладки см. в разделе Настройка сеансов отладки CMake.
Чтобы настроить отладку для базы кода, выберите в контекстном меню обозревателя решений пункт Параметры отладки и запуска. Также его можно открыть, щелкнув исполняемый файл правой кнопкой мыши.
В диалоговом окне Выбор отладчика выберите нужный вариант и нажмите кнопку Выбрать.
Если файла launch.vs.json еще нет, он будет автоматически создан.
Теперь щелкните правой кнопкой мыши исполняемый файл в обозревателе решений и выберите команду Назначить автозапускаемым элементом.
Теперь этот исполняемый файл будет отмечен как автозапускаемый элемент и его имя отобразится на кнопке Пуск на панели инструментов отладки.
Нажатие клавиши F5 запускает отладчик, который будет останавливаться на всех заданных точках останова. Все обычные окна отладчика будут доступны и активны.
Дополнительные сведения о настраиваемых задачах сборки и отладки в проектах открытых папок C++ см. в статье Open Folder support for C++ build systems in Visual Studio (Поддержка открытых папок для систем сборки C++ в Visual Studio).
Указание аргументов для отладки
Когда вы сохраните этот файл, имя новой конфигурации отобразится в раскрывающемся списке для целевого объекта отладки. Вы можете выбрать ее, чтобы запустить отладчик. Можно создать любое количество конфигураций отладки.
Дополнительные файлы параметров
Помимо трех файлов .json, которые описаны в этом разделе, Visual Studio считывает параметры из нескольких дополнительных файлов, если обнаружит их в базе кода.
.vscode\settings.json
Вы можете определить в базе кода любое количество файлов .vscode\settings.json. Параметры из этого файла применяются к каталогу на один уровень выше соответствующего .vscode и ко всем его подкаталогам.
.gitignore
Файлы .gitignore позволяют указать Git, что некоторые файлы следует игнорировать. Здесь вы перечисляете файлы и каталоги, которые не нужно регистрировать в репозитории. Файлы .gitignore обычно включаются в базу кода, чтобы все разработчики базы кода могли использовать эти параметры. Visual Studio считывает шаблоны из файлов .gitignore для фильтрации элементов при отображении и в некоторых средствах поиска.
Параметры из файла .gitignore применяются к родительскому каталогу файла и всем его подкаталогам.
How can I export settings?
How is it possible to export all Visual Studio Code settings and plugins and import them to another machine?
11 Answers 11
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
With the current version of Visual Studio Code as of this writing (1.22.1), you can find your settings in
/Library/Application Support/Code/User/ on Mac OS X (thank you, Christophe De Troyer)
Your extensions are in
Alternately, just go to the Extensions, show installed extensions, and install those on your target installation. For me, copying the extensions worked just fine, but it may be extension-specific, particularly if moving between platforms, depending on what the extension does.
/.vscode/extensions and (2)
/.vscode/settings. Then I’d create symlinks to the paths in your answer according to the specific OS. Once it’s done, I just put my
/ folder under version control. Like this, I keep my dotfiles and vscode config all in one repo.
/Library/Application Support/Code folder
There is an extension for Visual Studio Code, called Settings Sync.
It synchronises your settings by gist (Gist by GitHub). It works the same as the Atom.io extension called settings-sync.
UPDATE:
This feature is now build in VS Code, it is worth to switch to official feature. (https://stackoverflow.com/a/64035356/2029818)
You can now sync all your settings across devices with VSCode’s built-in Settings Sync. It’s found under Code > Preferences > Turn on Settings Sync.
Similar to the answer given by Big Rich you can do the following:
This will list out your extensions with the command to install them so you can just copy and paste the entire output into your other machine:
It is taken from the answer given here.
Note: Make sure you have added VS Code to your path beforehand. On mac you can do the following:
For posterity, this post mentions,
in the latest release of Visual Studio Code (May 2016) it is now possible to list the installed extension in the command line
On Mac, execute something like:
You can now synchronise all your settings across devices with Visual Studio Code’s built-in Settings Sync. It’s found under menu File → Preferences → Turn on Settings Sync.
Read more about it in the official documentation here.
Your user settings are in
If you’re not concerned about synchronising and it’s a one-time thing, you can just copy the files keybindings.json and settings.json to the corresponding folder on your new machine.
Your extensions are in the
/.vscode folder. Most extensions aren’t using any native bindings and they should be working properly when copied over. You can manually reinstall those who do not.
Using the script, which Big Rich had written before, with one more change, I can totally synchronise all extensions almost automatically.
Script
I’ve made a Python script for exporting Visual Studio Code settings into a single ZIP file:
You can upload the ZIP file to external storage.
PS: You may implement the vsc-settings.py import subcommand for me.
Portable Mode instructs Visual Studio Code to store all its configuration and plugins in a specific directory (called data/ in Windows and Linux and code-portable-data in macOS).
At any time you could copy the data directory and copy it on another installation.
I did this (Linux)
I then ran the script on the target machine.
Often there are questions about the Java settings in Visual Studio Code. This is a big question and can involve advanced user knowledge to accomplish. But there is simple way to get the existing Java settings from Visual Studio Code and copy these setting for use on another PC. This post is using recent versions of Visual Studio Code and JDK in mid-December 2020.
There are several screen shots (below) that accompany this post which should provide enough information for the visual learners.
First things first, open Visual Studio Code and either open an existing Java folder-file or create a new Java file in Visual Studio Code. Then look at the lower right corner of Visual Studio Code (on the blue command bar). The Visual Studio Code should be displaying an icon showing the version of the Java Standard Edition (Java SE) being used. The version being on this PC today is JavaSE-15. (link 1)
The settings.json file shows various settings used for coding different programming languages (Python, R, and Java). Near the bottom of the settings.json file shows the settings this User uses in Visual Studio Code for programming Java.
VS Code: вам не нужно это расширение
Перевод статьи «VS Code: You don’t need that extension».
Недавно я углубился в настройки VS Code и сделал несколько любопытных открытий. В редакторе есть довольно много функций и настроек, которые делают то же самое, что и многие популярные плагины.
1. Автоматическое переименование тегов и закрывающие теги
Расширения
Настройка
Название этого параметра несколько расплывчатое и неясное, поэтому многие люди так никогда его и не находят! В настоящее время поддерживаются HTML-файлы и есть открытый issue по добавлению поддержки JSX.
settings.json:
2. Синхронизация настроек
VS Code теперь поддерживает синхронизацию настроек на разных машинах. Эту фичу можно посмотреть в превью на VS Code Insiders. Очень скоро она попадет в стандартную версию.
Я сейчас испытываю этот функционал и пока вроде все хорошо.
Расширения
Settings Sync (1,8 млн. загрузок): синхронизирует ваши настройки, сочетания клавиш, сниппеты, расширения и файлы запуска с GitHub Gist.
Функционал VS Code и его настройка
Почитать об этом функционале подробнее можно в руководстве пользователя. А вот как выглядят настройки:
Вы можете использовать аккаунт Microsoft или GitHub и выбрать, что именно хотите синхронизировать.
3. Автоимпорт модулей
Управление импортами модулей JavaScript и TypeScript может стать настоящей головной болью, особенно если вы хотите переорганизовать свой проект или провести рефакторинг кода. Было бы очень желательно это автоматизировать!
Расширения
Настройки
JavaScript > Suggest: Auto Imports : «Включает/отключает предложения автоимпорта. Необходимо использование в рабочем пространстве Typescript 2.6.1 или новее». Значение по умолчанию: true.
TypeScript > Suggest: Auto Imports : все то же самое, что и для JavaScript.
JavaScript > Update Imports on File Move: Enabled : «Включает/отключает автоматическое обновление путей импорта, когда вы переименовываете или перемещаете файл в VS Code. Необходимо использование в рабочем пространстве Typescript 2.9 или новее». Значение по умолчанию: prompt.
TypeScript > Update Imports on File Move: Enabled : все то же самое, что и для JavaScript.
settings.json
Кроме того, если вы хотите, чтобы ваши импорты упорядочивались при сохранении, вы можете добавить настройку, приведенную ниже. Это удалит неиспользуемые предложения импорта и поместит предложения импорта с абсолютными путями сверху. Я большой поклонник таких задач «настрой и забудь».
4. Сниппеты HTML и CSS
Возможно, вы хотите создавать какие-то бойлерплейты для быстрого старта или добавлять отрывки кода для сохранения сочетаний клавиш. Расширения, перечисленные ниже, удовлетворяют похожие, но при этом слегка отличающиеся нужды.
Расширения
Функционал VS Code
В VS Code встроен Emmet. Он предлагает сокращение и раскрытие сниппетов для HTML и CSS. По умолчанию Emmet включен для файлов html, haml, pug, slim, jsx, xml, xsl, css, scss, sass, less and stylus. Подробнее можно почитать в руководстве пользователя VS Code.
Вам доступны сокращения, использующие CSS-селекторы, например:
что дает такой результат:
Это лишь беглый обзор того, что касается HTML. Но аналогичные возможности есть и для CSS. Например, мне очень нравится автоматическое добавление vendor-префиксов. Подробнее читайте в документации Emmet, а на будущее — вот вам шпаргалка.
Сниппеты можно кастомизировать, а также создавать свои. Делается это путем добавления их в json-файл snippets.json.
При желании можно включить Emmet для большего числа языков, например, для Vue. Для этого нужно добавить строку в settings.json :
Я большой поклонник Emmet. Когда привыкаешь к использованию сниппетов, писать и редактировать HTML и CSS получается просто молниеносно быстро.
5. Фейковый текст (рыба)
Часто возникает необходимость вставить какой-нибудь бессодержательный текст, чтобы заполнить веб-страницу и увидеть, как выглядит UI. Наверняка вам знакомы генераторы «lorem ipsum».
Расширение
Lorem Ipsum (168 тысяч загрузок)
Функционал VS Code
Как мы уже говорили, в VS Code встроен Emmet, а у него есть сокращение lorem. Наберите « lorem», нажмите Tab, и получите параграф на 30 слов.
Вы можете использовать этот функционал для генерации самых разных блоков. Например, сокращение «p*2>lorem» сгенерирует примерно такое:
6. Автообрезка
Автоматическое удаление повторяющихся пробелов. Замена, которую я предлагаю, работает не точно так же, как расширения. Расширения обрезают пробелы по мере редактирования или по команде, а настройки VS Code позволяют обрезать пробелы при сохранении.
Расширения
Trailing Spaces (447 тысячи загрузок): «Подсвечивайте повторяющиеся пробелы и моментально удаляйте их!»
Autotrim (15 тысяч загрузок): «После редактирования строк кода (например, удаления слов) часто остаются повторяющиеся пробелы. Это расширение отслеживает, на каких строках находится курсор, и удаляет повторяющиеся пробелы в тех строках, где курсора нет».
Настройки VS Code
settings.json
А вы знаете какие-нибудь настройки VS Code, позволяющие обходиться без популярных расширений? Поделитесь в комментариях!
VSCode Settings.json is empty
I just install the latest version of the VS Code on my Win 10 x64, before that I install Python as well, but nothing else. When I open the VS Code, it seems my Settings.json is empty (just my theme and zoom level are there).
I opened the Settings.json from settings with clicking on the icon that you can see in the bellow image (noted with a red circle in the top right side) or with searching the JSON keyword in the setting (result is the same)
But in this file I just have two lines of code which you can see in the below image:
But I think it has to bee a big file with lots of settings and so on, even I check this file in this path: %APPDATA%\Code\User\settings.json and it was empty and just have this two lines of code.
Can you help in these questions:
Настройка задач сборки и отладки для режима разработки «Открытая папка»
Visual Studio поддерживает множество разных языков и баз кода, но не все существующие варианты. Если вы откроете в Visual Studio папку с кодом, который поддерживает Visual Studio, его можно выполнить немедленно и без дополнительных настроек.
Если в базе кода используются пользовательские средства сборки, которые не распознаются Visual Studio, для выполнения и отладки такого кода в Visual Studio требуются определенные сведения о конфигурации. Чтобы указать Visual Studio правила сборки вашего кода, определите задачи сборки. Создав одну или несколько задач сборки, вы сможете указать в них все элементы, которые потребуются для сборки и выполнения кода на определенном языке. Кроме того, можно создавать произвольные задачи с практически неограниченными возможностями. Например, с помощью задач можно вывести список содержимого папки или переименовать файл.
Чтобы настроить базу кода, не относящуюся к конкретному проекту, воспользуйтесь следующими файлами .json:
Имя файла | Цель |
---|---|
tasks.vs.json | Определяет настраиваемые команды сборки и параметры компилятора, а также произвольные (не имеющие отношения к сборке) задачи. Доступ к файлу можно получить в обозревателе решений, выбрав пункт контекстного меню Настройка задач. |
launch.vs.json | Определяет аргументы командной строки для отладки. Доступ к файлу можно получить в обозревателе решений, выбрав пункт контекстного меню Параметры отладки и запуска. |
Описанные файлы .json находятся в скрытой папке с именем .vs в корневой папке базы кода. Файлы tasks.vs.json и launch.vs.json создаются в среде Visual Studio по мере необходимости, то есть когда вы выбираете в обозревателе решений действия Настройка задач или Параметры отладки и запуска для файла или папки. Эти файлы .json скрыты, потому что пользователи обычно не добавляют их в систему управления версиями. Но если требуется возможность записать их в систему управления версиями, с помощью файловой системы перетащите файлы в корневую папку базы кода, где они будут видны в Обозревателе решений и в системе управления версиями.
Чтобы просмотреть скрытые папки в Visual Studio, нажмите кнопку Показать все файлы на панели инструментов обозревателя решений.
Определение задач в файле tasks.vs.json
Вы можете автоматизировать скрипты сборки и любые внешние операции с файлами, размещенными в текущей рабочей области, запуская их как задачи в интегрированной среде разработки. Чтобы настроить новую задачу, щелкните правой кнопкой мыши нужный файл или папку и выберите Настройка задач.
В среде разработки откроется (или будет создан, если его еще нет) файл tasks.vs.json в папке .vs. Можно определить в этом файле задачу сборки или произвольную задачу, а затем вызывать ее по имени в контекстном меню обозревателя решений.
Настраиваемые задачи можно размещать в отдельных файлах или во всех файлах определенного типа. Например, можно определить во всех файлах пакета NuGet задачу «Восстановить пакеты» или поместить во все файлы исходного кода задачу статического анализа, например анализатор кода для всех JS-файлов.
Определение настраиваемых задач сборки
Если в базе кода используются настраиваемые средства сборки, которые не распознаются в Visual Studio, вам не удастся выполнить и отладить код в Visual Studio без нескольких дополнительных настроек. Visual Studio поддерживает задачи сборки, в которых вы можете указать Visual Studio правила сборки, перестроения и очистки кода. Файл задачи сборки tasks.vs.json связывает внутренний цикл разработки Visual Studio с пользовательскими средствами сборки, применяемыми для базы кода.
Давайте рассмотрим пример базы кода, которая состоит из одного файла на языке C# с именем hello.cs. Файл makefile для такой базы кода может выглядеть следующим образом:
Этот файл makefile содержит целевые объекты сборки, очистки и перестроения, и вы можете определить для него указанный ниже файл tasks.vs.json. Он содержит три задачи сборки (для сборки, перестроения и очистки), для которых применяется средство сборки NMAKE.
Когда вы определите в файле tasks.vs.json задачи сборки, в контекстном меню обозревателя решений для соответствующих файлов появятся дополнительные пункты. В нашем примере для всех файлов makefile в контекстное меню добавляются действия «Сборка», «Перестроить» и «Очистить».
Если вы выберете любой из этих вариантов, будет выполнена соответствующая задача. Выходные данные отображаются в окне Вывод, а ошибки сборки — в окне Список ошибок.
Определение произвольных задач
Вы можете описать в файле tasks.vs.json произвольную задачу, которая предназначена для выполнения любого действия. Например, можно определить задачу для отображения имени файла, выбранного в окне вывода, или списка файлов в указанном каталоге.
Ниже представлен пример файла tasks.vs.json, который определяет одну задачу. При вызове этой задачи отображается имя выбранного файла .js.
Сохранив файл tasks.vs.json, вы можете щелкнуть правой кнопкой мыши любой файл .js и выбрать команду Echo filename (Отобразить имя файла). Имя файла будет отображено в окне Вывод.
Если в базе кода нет файлов tasks.vs.json, вы можете создать такой файл с помощью команды Настройка задач в контекстном меню обозревателя решений. Эту команду также можно вызвать, щелкнув файл правой кнопки мыши.
В следующем примере определяется задача перечисления всех файлов и вложенных папок из каталога bin.
Эта задача применяется ко всем файлам. Открыв в обозревателе решений контекстное меню для любого файла, вы увидите в нижней части этого меню задачу с именем List Outputs (Перечислить выходные объекты). Если выбрать команду List Outputs (Перечислить выходные объекты), все содержимое каталога bin выводится в окне Вывод в Visual Studio.
Область действия параметров
В корневой папке и вложенных папках базы кода может быть несколько файлов tasks.vs.json. Такой подход позволяет гибко настраивать разные правила для разных каталогов в базе кода. Visual Studio объединяет или переопределяет параметры для разных разделов базы кода, используя следующий приоритет файлов:
Эти правила агрегирования применяются к tasks.vs.json. Сведения о правилах агрегирования параметров для другого файла см. в посвященном ему разделе этой статьи.
Свойства для tasks.vs.json
В этом разделе описаны некоторые свойства, которые можно задать в файле tasks.vs.json.
appliesTo
Маска файла | Описание |
---|---|
«*» | Задача доступна для всех файлов и папок в рабочей области. |
«*/» | Задача доступна для всех папок в рабочей области. |
«*.js» | Задача доступна для всех файлов с расширением JS в рабочей области. |
«/*.js» | Задача доступна для всех файлов с расширением JS в корневой папке рабочей области. |
«src/*/» | Задача доступна для всех подпапок в папке SRC. |
«makefile» | Задача доступна для всех файлов makefile в рабочей области. |
«/makefile» | Задача доступна только для файлов makefile в корневой папке рабочей области. |
Макросы для tasks.vs.json
Настройка отладки с помощью launch.vs.json
Сведения о настройке проектов CMake для отладки см. в разделе Настройка сеансов отладки CMake.
Чтобы настроить отладку для базы кода, выберите в контекстном меню обозревателя решений пункт Параметры отладки и запуска. Также его можно открыть, щелкнув исполняемый файл правой кнопкой мыши.
В диалоговом окне Выбор отладчика выберите нужный вариант и нажмите кнопку Выбрать.
Если файла launch.vs.json еще нет, он будет автоматически создан.
Теперь щелкните правой кнопкой мыши исполняемый файл в обозревателе решений и выберите команду Назначить автозапускаемым элементом.
Теперь этот исполняемый файл будет отмечен как автозапускаемый элемент и его имя отобразится на кнопке Пуск на панели инструментов отладки.
Нажатие клавиши F5 запускает отладчик, который будет останавливаться на всех заданных точках останова. Все обычные окна отладчика будут доступны и активны.
Дополнительные сведения о настраиваемых задачах сборки и отладки в проектах открытых папок C++ см. в статье Open Folder support for C++ build systems in Visual Studio (Поддержка открытых папок для систем сборки C++ в Visual Studio).
Указание аргументов для отладки
Когда вы сохраните этот файл, имя новой конфигурации отобразится в раскрывающемся списке для целевого объекта отладки. Вы можете выбрать ее, чтобы запустить отладчик. Можно создать любое количество конфигураций отладки.
Дополнительные файлы параметров
Помимо трех файлов .json, которые описаны в этом разделе, Visual Studio считывает параметры из нескольких дополнительных файлов, если обнаружит их в базе кода.
.vscode\settings.json
Вы можете определить в базе кода любое количество файлов .vscode\settings.json. Параметры из этого файла применяются к каталогу на один уровень выше соответствующего .vscode и ко всем его подкаталогам.
.gitignore
Файлы .gitignore позволяют указать Git, что некоторые файлы следует игнорировать. Здесь вы перечисляете файлы и каталоги, которые не нужно регистрировать в репозитории. Файлы .gitignore обычно включаются в базу кода, чтобы все разработчики базы кода могли использовать эти параметры. Visual Studio считывает шаблоны из файлов .gitignore для фильтрации элементов при отображении и в некоторых средствах поиска.
Параметры из файла .gitignore применяются к родительскому каталогу файла и всем его подкаталогам.
In the Visual Stuido Code demo minute 28:57-29:20 and 30:20-31:10, some cool JSON code completion is shown.
Where and how do I add a schema for my JSON files to a project?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The association of JSON schemas to files is done in the settings (File, Preferences, User Settings or Workspace Settings), under the property ‘json.schemas’.
This is an example how the JSON schema for bower is associated to the bower schema.
You can also use schemas located in your workspace or define a schema right in the settings itself. Check https://code.visualstudio.com/docs/languages/json for examples.
This is the intellisense I was talking about. JSON Schema has the list of possible JSON properties in your current cursor position and VS Code can pull out that list of intellisense.
Note that, every official JSON should have a concrete JSON Schema to prove the data integrity. This answer is still valid!
In User Settings», i.e. as an element in the users settings.json in ‘C:\Users\\AppData\Roaming\Code\User’
The Folder takes precedence over Workspace, and Workspace over User
Is there any way to sync my Visual Studio Code settings between instances?
I’d like to be able to sync my VS Code user settings (File > Preferences > User Settings) to the cloud somehow so I can easily share them between multiple installations, as in Windows 10 and Visual Studio.
Is there a supported way of doing this? Direct support in Code would be great, but otherwise being able to move my settings.json location to a Dropbox or OneDrive folder would work too.
I’m looking specifically for a way of doing this automatically and silently. Manually exporting/importing is too cumbersome and isn’t what I’m looking for.
Update: this is now a built-in feature in VS Code.
10 Answers 10
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I have developed an extension that will sync all your Visual Studio Code Settings across multiple instances.
Key Features
It Sync
Detail Documentation Source
You can make a hard link from the directory containing user settings to your sync directory of applications such as Dropbox or OneDrive.
mklink /H /J X:\Your\Sync\Dir %APPDATA%\Code\User
on your computers with Visual Studio Code to achieve the synchronization.
Then, on another computer, you may delete the %APPDATA%\Code\User folder, and type:
mklink /H /J %APPDATA%\Code\User X:\Your\Sync\Dir
to retrieve the synchronized settings.
Aha, you can try my VSCode extension: Syncing.
Hoping you’ll like it. 🙂
A Quick Guide
Get your own GitHub Personal Access Token :
Login to your GitHub Settings page.
Copy and backup your token.
Sync your settings:
Upload:
Enter your Gist ID (or leave it blank to create automatically).
After uploading, you can find your settings and the corresponding Gist ID in your GitHub Gist.
Download:
Enter your GitHub Personal Access Token (or leave it blank if you want to download from a public Gist)
Enter your Gist ID (or a public Gist ID ).
Preview features
Preview features are not ready for release but are functional enough to use. We welcome your early feedback while they are under development.
Settings Sync
Settings Sync is now available for preview in the stable release 🎉. Refer to the user guide for more information & FAQs.
Feature is now called Settings Sync also in the product. All of its references & settings are renamed to be aligned.
In v1.45 it looks like you will be able to login to the built-in Settings Sync via github, see https://github.com/microsoft/vscode/issues/95160#event-3266867554 (Support GitHub logins in settings sync). And the v1.45 Release Notes.
In v1.43 as a preview feature (so in the Insiders’ Build only) is settings sync. See https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_43.md#settings-sync
We have been working the last couple of months to support synchronizing VS Code settings, extensions, and keyboard shortcuts across machines (popular feature request #2743). In this milestone, we are happy to announce that this feature is ready for preview from our next 1.44.0-insider release. You can now have your customizations synchronized in all your VS Code installs across all your machines. You can also bootstrap VS Code with your personal customizations on a fresh machine with minimal effort. Following video demonstrates this:
Supports detecting conflicts in settings and keybindings while synchronizing. Conflicts are shown using the diff editor with incoming (cloud) changes on the left side and local changes on the right side. You can resolve the conflicts by editing in the right side editor and merge the changes using the actions provided in the editor.
Supported Features
Currently Settings, Keyboard Shortcuts, Extensions, and the Display Language are synchronized but we are planning to add more. You can review our list of proposed Setting Sync features.
Settings Sync activity can be monitored in the Log (Sync) output view. All local customizations are backed up for last 30 days (atleast 10) in the disk whenever they are changed during synchronization. You can use the command Sync: Open Local Backups Folder to go the backups location and retain your old customizations.
(and a few gifs at the release note link)
Settings Sync uses a Microsoft account to store your VS Code customizations for synchronization and therefore you would need an account to use this. Refer to the Settings Sync documentation for more information and help.
How to reset settings in Visual Studio Code?
It’s a simple thing and I was pretty sure it’s well described, but surprisingly it is not so obvious.
Can someone give me some help with restoring default settings in Visual Studio Code? I’ve hidden menu bar by accident and I can’t find no way to show it back.
13 Answers 13
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
As for your settings, you can open your user settings through the command palette:
Click the «sheet» icon to open the settings.json file:
From there you can delete the file’s contents and save to reset your settings.
For a more manual route, the settings files are located in the following locations:
Extensions are located in the following locations:
If you want to reset everything, go to %userprofile%\AppData\Roaming\Code and delete the whole folder after you uninstall the VS code, then install it again.
Also in %userprofile%\.vscode delete extensions folder in case you want to delete all extensions.
This may be overkill, but it seemed to work for me (on a Mac):
After I ran that, and restarted VSC, it showed the the «Welcome» screen, which I took to mean that it was starting from scratch.
If you want to start afresh, deleting the settings.json file from your user’s profile will do the trick.
But if you don’t want to reset everything, it is still possible through settings menu.
You can search for the setting that you want to revert back using search box.
You will see some settings with the left blue line, it means you’ve modified that one.
If you take your cursor to that setting, a gear button will appear. You can click this to restore that setting.
You can also use the drop-down below that setting and change it to default.
How to change visual studio code settings
I am trying to changes visual studio code settings.json but it is not working. I have updated this in C:\Users\Userid\AppData\Roaming\Code\User\settings.json but not working. How to edit settings.json file in vs code?
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
VSCode’s settings are split into 2 categories: User and Workspace.
User settings
Settings that apply globally to any instance of VS Code you open.
VSCode settings pane with User Settings tab open
Editing JSON schemas
The VSCode settings page does not allow direct editing of JSON Schemas. To edit JSON schema settings: 1. Search JSON schemas in the VSCode settings page 2. Click «edit in settings.json» 3. Edit settings 4. Done!
JSON schema setting in VSCode
Workspace settings
Settings stored inside your workspace and only apply when the workspace is opened.
Workspace settings override user settings.
To edit workspace settings, follow steps for user settings, except click the Workspace Settings tab instead. Note that workspace settings will override user settings
How to exclude settings.json from VS Code search
I thought maybe I would achieve it with this:
But without luck.
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
And reload editor. It will remove from search settings.json in all folders.
Note: if settings.json is opened it will still emerge in the search result.
If you hover over the filename settings.json in the left panel you can copy the path by right-clicking. I get something like:
with «experimental» as the workspace root. Then it is a question of how/whether to escape those backslashes but a little experimentation should get you there.
How to Customize Visual Studio Code
Visual Studio Code, Microsoft’s new open-source code editor provides developers with many awesome features that significantly facilitate the process of source code editing. Besides, Visual Studio Code also makes sure users won’t be bored when they work with it, as it allows them to customize several parts of its appearance, such as colours, fonts, spacing, and text formatting, just like many functionalities, such as linting and validaton rules.
How to Set a Colour Theme on VS Code
Visual Studio Code allows you to set a custom colour theme for your editor.
To put a pre-made theme into use, click on the File > Preferences > Color Theme menu in the top menu bar. When you hit “Enter”, the Command Palette pops up, and displays a dropdown list of the themes you can choose from.
You can achieve the same effect if you press F1 to open the Command Palette, and type the Preferences: Color Theme command into the input field.
As you roll over the options in the dropdown list, the appearance of the workspace changes real-time, so you can quickly see which theme fits your needs the best.
I chooe the “High Contrast” colour theme, as my eyes are not the best. Here’s what my view looks like.
How to Install a Theme from VS Code Marketplace
If you don’t like any of the colour themes VS Code offers by default, you can download many others from the VS Code Marketplace.
Here you can take a look at the themes the Marketplace currently has. If you want to install a theme from the Marketplace, hit F1 right inside your VS Code editor in order to open the Command Palette, then type the ext install command into the input field, finally choose the Extensions: Install Extension option from the list that pops up.
When you click on this option, a new instance of Command Palette pops up. Type the «ext install theme» command into the new input field, and you will get a list of all the themes that are available from the VS Code Marketplace.
I choose the theme called “Material Theme Kit”, and install it by clicking on it. To have the new theme in the Color Theme list, in the same place where the other default themes are, you need to restart VS Code. After restarting, the new theme appears in the theme list, and you can set it from the Command Palette.
With the new Material Theme, my editor now looks like this:
You can go back to the previous theme (like I did, because I still prefer that theme) or you can play around some more with other themes to see which is the most suitable for you.
If you want, you can also create your custom theme, and publish it on VS Code Marketplace by using the vsce extension manager tool.
Change User and Workspace Settings
VS Code doesn’t only allow you to set a custom theme, but you can also configure many other settings, such as formatting rules, usage of different features, crash reports, HTTP settings, file associations, linting rules, and more.
You can do this by editing two configuration files, both in JSON format. Don’t worry, you don’t need to be a pro, as VS Code offers a pretty straightforward and intuitive way to quickly add your customizations.
At first, let’s see what is the difference between the two configuration files. VS Code has two scopes (global and local) for settings, hence the two separate files:
The global settings.json file can be found in the folder where your operating system stores every other app-related configuration files, respectively:
So when do you use the settings.json files?
If you want VS Code to use your custom configuration rules in all your projects, put them into the global settings.json file.
If you want your settings to only be valid in your current project, place them into the workspace-related settings.json file.
Workspace settings override the global settings, so be careful.
Global settings are called “User Settings” in VS Code. Open them either by clicking on the File > Preferences > User Settings menu, or by beginning to type the expression “User Settings” into the Command Palette (open it with F1).
VS Code opens two panes next to each other: the left one contains all the options that are possible to configure, and the right one displays the global settings.json file. You need to place your custom configuration rules into this file.
As you can see, you don’t need to do anything else, just copy-paste the settings you want to change from the left side to the right, and add the modified values.
Variables Reference
Visual Studio Code supports variable substitution in Debugging and Task configuration files as well as some select settings. Variable substitution is supported inside some key and value strings in launch.json and tasks.json files using $ syntax.
Predefined variables
The following predefined variables are supported:
Predefined variables examples
Supposing that you have the following requirements:
So you will have the following values for each variable:
Tip: Use IntelliSense inside string values for tasks.json and launch.json to get a full list of predefined variables.
Variables scoped per workspace folder
By appending the root folder’s name to a variable (separated by a colon), it is possible to reach into sibling root folders of a workspace. Without the root folder name, the variable is scoped to the same folder where it is used.
Environment variables
Configuration variables
Command variables
If the predefined variables from above are not sufficient, you can use any VS Code command as a variable through the $ syntax.
A command variable is replaced with the (string) result from the command evaluation. The implementation of a command can range from a simple calculation with no UI, to some sophisticated functionality based on the UI features available via VS Code’s extension API. If the command returns anything other than a string, then the variable replacement will not complete. Command variables must return a string.
An example of this functionality is in VS Code’s Node.js debugger extension, which provides an interactive command extension.pickNodeProcess for selecting a single process from the list of all running Node.js processes. The command returns the process ID of the selected process. This makes it possible to use the extension.pickNodeProcess command in an Attach by Process ID launch configuration in the following way:
Input variables
Command variables are already powerful but they lack a mechanism to configure the command being run for a specific use case. For example, it is not possible to pass a prompt message or a default value to a generic «user input prompt».
The following example shows the overall structure of a tasks.json that makes use of input variables:
Currently VS Code supports three types of input variables:
Each type requires additional configuration attributes:
Below is an example of a tasks.json that illustrates the use of inputs using Angular CLI:
Running the example:
The following example shows how to use a user input variable of type command in a debug configuration that lets the user pick a test case from a list of all test cases found in a specific folder. It is assumed that some extension provides an extension.mochaSupport.testPicker command that locates all test cases in a configurable location and shows a picker UI to pick one of them. The arguments for a command input are defined by the command itself.
Command inputs can also be used with tasks. In this example, the built-in Terminate Task command is used. It can accept an argument to terminate all tasks.
Common questions
Details of variable substitution in a debug configuration or task
Variable substitution in debug configurations or tasks is a two pass process:
A consequence of this is that the evaluation of a variable (for example, a command-based variable implemented in an extension) has no access to other substituted variables in the debug configuration or task. It only sees the original variables. This means that variables cannot depend on each other (which ensures isolation and makes substitution robust against evaluation order).
Is variable substitution supported in User and Workspace settings?
Refer to the comments in the Settings editor ( ⌘, (Windows, Linux Ctrl+, ) ) to learn about setting specific variables.
How to change visual studio code settings
I am trying to changes visual studio code settings.json but it is not working. I have updated this in C:\Users\Userid\AppData\Roaming\Code\User\settings.json but not working. How to edit settings.json file in vs code?
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
VSCode’s settings are split into 2 categories: User and Workspace.
User settings
Settings that apply globally to any instance of VS Code you open.
VSCode settings pane with User Settings tab open
Editing JSON schemas
The VSCode settings page does not allow direct editing of JSON Schemas. To edit JSON schema settings: 1. Search JSON schemas in the VSCode settings page 2. Click «edit in settings.json» 3. Edit settings 4. Done!
JSON schema setting in VSCode
Workspace settings
Settings stored inside your workspace and only apply when the workspace is opened.
Workspace settings override user settings.
To edit workspace settings, follow steps for user settings, except click the Workspace Settings tab instead. Note that workspace settings will override user settings
VS Code: How to Use Custom Settings for a Project
September 23, 2021
February 9, 2022
February 9, 2022
February 8, 2022
February 9, 2022
February 9, 2022
September 7, 2021
This article shows you how to use some specific settings for only a particular project in VS Code (Visual Studio Code). This will come in handy when you have a project that requires special settings but you don’t want to change the current global settings.
Using GUI (Graphic User Interface)
1. Open your project with VS Code and head to the Settings page:
2. Select the Workspace tab and made your changes here.
For example, I will increase the font size to 24 for a project named “react_ts_kindacode” like this:
Advertisements The update only affects the “react_ts_kindacode” project but not others:
Contribution Points
Contribution Points are a set of JSON declarations that you make in the contributes field of the package.json Extension Manifest. Your extension registers Contribution Points to extend various functionalities within Visual Studio Code. Here is a list of all available Contribution Points:
contributes.breakpoints
Usually a debugger extension will also have a contributes.breakpoints entry where the extension lists the language file types for which setting breakpoints will be enabled.
contributes.colors
Contributes new themable colors. These colors can be used by the extension in editor decorators and in the status bar. Once defined, users can customize the color in the workspace.colorCustomization setting and user themes can set the color value.
Color default values can be defined for light, dark and high contrast theme and can either be a reference to an existing color or a Color Hex Value.
Extensions can consume new and existing theme colors with the ThemeColor API:
contributes.commands
Contribute the UI for a command consisting of a title and (optionally) an icon, category, and enabled state. Enablement is expressed with when clauses. By default, commands show in the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) but they can also show in other menus.
Note: When a command is invoked (from a key binding, from the Command Palette, any other menu, or programmatically), VS Code will emit an activationEvent onCommand:$
.
Note: When using icons from product icons, setting light and dark will disable the icon. The correct syntax is «icon»: «$(book)»
command example
See the Commands Extension Guide to learn more about using commands in VS Code extensions.
Command icon specifications
contributes.configuration
Contribute configuration keys that will be exposed to the user. The user will be able to set these configuration options as User Settings or as Workspace Settings, either by using the Settings editor or by editing the JSON settings file directly.
This section can either be a single object, representing a single category of settings, or an array of objects, representing multiple categories of settings. If there are multiple categories of settings, the Settings editor will show a submenu in the table of contents for that extension, and the title keys will be used for the submenu entry names.
Configuration example
Configuration schema
Your configuration entry is used both to provide intellisense when editing your settings in the JSON editor, and to define the way they appear in the settings UI.
title
The title 1️⃣️ of a category is the heading used for that category.
Note that if the extension has multiple categories of extensions, and the title of one of the categories is the same as the extension display name, then the settings for that category will be placed directly below the main extension heading, no matter what the order field is set to.
For both the title and displayName fields, words like «Extension», «Configuration», and «Settings» are redundant.
properties
The properties 2️⃣ in your configuration will be a dictionary of configuration properties.
Entries will be grouped according to the hierarchy established in your keys. So for example, these entries
will appear in a single group like this:
Blame: Format
Blame › Heatmap: Enabled
Blame › Heatmap: Location
Otherwise, properties without an explicit order field appear in alphabetical order (not the order in which they’re listed in the manifest).
Configuration property schema
Configuration keys are defined using a superset of JSON Schema.
description / markdownDescription
Your description 3️⃣ appears after the title and before the input field, except for booleans, where the description is used as the label for the checkbox. 6️⃣
type
A string setting can be rendered with a multiline text input if it sets «editPresentation»: «multilineText» on the configuration entry.
For boolean entries, the description (or markdownDescription ) will be used as the label for the checkbox.
If an object or array type setting can also contain other types like nested objects, arrays, or null, then the value won’t be rendered in the settings UI and can only be modified by editing the JSON directly. Users will see a link to Edit in settings.json as shown in the screenshot above. 8️⃣
order
Both categories and the settings within those categories can take an integer order type property, which gives a reference to how they should be sorted relative to other categories and/or settings.
If two categories have order properties, the category with the lower order number comes first. If a category is not given an order property, it appears after categories that were given that property.
If two settings within the same category have order properties, the setting with the lower order number comes first. If another setting within that same category is not given an order property, it will appear after settings in that category that were given that property.
If two categories have the same order property value, or if two settings within the same category have the same order property value, then they will be sorted in increasing alphabetical order within the settings UI.
enum / enumDescriptions
If you provide an array of items under the enum 7️⃣ property, the settings UI will render a dropdown menu.
You can also provide an enumDescriptions property, which provides descriptive text rendered at the bottom of the dropdown:
deprecationMessage / markdownDeprecationMessage
Other JSON Schema properties
You can use any of the validation JSON Schema properties to describe other constraints on configuration values:
Unsupported JSON Schema properties
Not supported in the configuration section are:
For more details on these and other features, see the JSON Schema Reference.
scope
A configuration setting can have one of the following possible scopes:
Below are example configuration scopes from the built-in Git extension:
You can see that git.alwaysSignOff has resource scope and can be set per user, workspace, or folder, while the ignored repositories list with window scope applies more globally for the VS Code window or workspace (which might be multi-root).
Linking to settings
In the settings UI, this is rendered as:
contributes.configurationDefaults
Contribute default language-specific editor configurations. This will override default editor configurations for the provided language.
The following example contributes default editor configurations for the markdown language:
Configuration default example
contributes.customEditors
The customEditors contribution point is how your extension tells VS Code about the custom editors that it provides. For example, VS Code needs to know what types of files your custom editor works with as well as how to identify your custom editor in any UI.
Here’s a basic customEditor contribution for the custom editor extension sample:
customEditors is an array, so your extension can contribute multiple custom editors.
The display name is shown to the user in VS Code UI such as the View: Reopen with dropdown.
The selector is an array of one or more glob patterns. These glob patterns are matched against file names to determine if the custom editor can be used for them. A filenamePattern such as *.png will enable the custom editor for all PNG files.
priority controls when a custom editor is used when a resource is open. Possible values are:
You can learn more in the Custom Editors extension guide.
contributes.debuggers
Contribute a debugger to VS Code. A debugger contribution has the following properties:
debugger example
contributes.grammars
Contribute a TextMate grammar to a language. You must provide the language this grammar applies to, the TextMate scopeName for the grammar and the file path.
grammar example
See the Syntax Highlight Guide to learn more about how to register TextMate grammars associated with a language to receive syntax highlighting.
contributes.icons
contributes.iconThemes
Contribute a file icon theme to VS Code. File icons are shown next to file names, indicating the file type.
You must specify an id (used in the settings), a label and the path to the file icon definition file.
file icon theme example
See the File Icon Theme Guide on how to create a File Icon Theme.
contributes.jsonValidation
Contribute a validation schema for a specific type of json file. The url value can be either a local path to a schema file included in the extension or a remote server URL such as a json schema store.
contributes.keybindings
Contribute a key binding rule defining what command should be invoked when the user presses a key combination. See the Key Bindings topic where key bindings are explained in detail.
Contributing a key binding will cause the Default Keyboard Shortcuts to display your rule, and every UI representation of the command will now show the key binding you have added. And, of course, when the user presses the key combination the command will be invoked.
Note: Because VS Code runs on Windows, macOS and Linux, where modifiers differ, you can use «key» to set the default key combination and overwrite it with a specific platform.
Note: When a command is invoked (from a key binding or from the Command Palette), VS Code will emit an activationEvent onCommand:$
.
keybinding example
Defining that Ctrl+F1 under Windows and Linux and Cmd+F1 under macOS trigger the «extension.sayHello» command:
contributes.languages
Contribute definition of a programming language. This will introduce a new language or enrich the knowledge VS Code has about a language.
The main effects of contributes.languages are:
language example
contributes.menus
Contribute a menu item for a command to the editor or Explorer. The menu item definition contains the command that should be invoked when selected and the condition under which the item should show. The latter is defined with the when clause, which uses the key bindings when clause contexts.
A command property indicates which command to run when selecting a menu item. A submenu property indicates which submenu to render in this location.
Last, a group property defines sorting and grouping of menu items. The navigation group is special as it will always be sorted to the top/beginning of a menu.
Note that when clauses apply to menus and enablement clauses to commands. The enablement applies to all menus and even keybindings while the when only applies to a single menu.
Currently extension writers can contribute to:
Note: When a command is invoked from a (context) menu, VS Code tries to infer the currently selected resource and passes that as a parameter when invoking the command. For instance, a menu item inside the Explorer is passed the URI of the selected resource and a menu item inside an editor is passed the URI of the document.
In addition to a title, commands can also define icons which VS Code will show in the editor title menu bar.
menu example
Here’s a command menu item:
Here’s a submenu menu item:
Context specific visibility of Command Palette menu items
The snippet below makes the ‘Hello World’ command only visible in the Command Palette when something is selected in the editor:
Sorting of groups
Menu items can be sorted into groups. They are sorted in lexicographical order with the following defaults/rules. You can add menu items to these groups or add new groups of menu items in between, below, or above.
The editor context menu has these default groups:
The explorer context menu has these default groups:
The editor tab context menu has these default groups:
The editor title menu has these default groups:
The Timeline view item context menu has these default groups:
The Extensions view context menu has these default groups:
Sorting inside groups
The order inside a group depends on the title or an order-attribute. The group-local order of a menu item is specified by appending @ to the group identifier as shown below:
contributes.problemMatchers
Contribute problem matcher patterns. These contributions work in both the output panel runner and in the terminal runner. Below is an example to contribute a problem matcher for the gcc compiler in an extension:
contributes.problemPatterns
Contributes named problem patterns that can be used in problem matchers (see above).
contributes.productIconThemes
Contribute a product icon theme to VS Code. Product icons are all icons used in VS Code except file icons and icons contributed from extensions.
You must specify an id (used in the settings), a label and the path to the icon definition file.
product icon theme example
See the Product Icon Theme Guide on how to create a Product Icon Theme.
contributes.resourceLabelFormatters
Contributes resource label formatters that specify how to display URIs everywhere in the workbench. For example here’s how an extension could contribute a formatter for URIs with scheme remotehub :
contributes.semanticTokenModifiers
Contributes new semantic token modifiers that can be highlighted via theme rules.
See the Semantic Highlighting Guide to read more about semantic highlighting.
contributes.semanticTokenScopes
Contributes mapping between semantic token types & modifiers and scopes either as a fallback or to support language-specific themes.
See the Semantic Highlighting Guide to read more about semantic highlighting.
contributes.semanticTokenTypes
Contributes new semantic token types that can be highlighted via theme rules.
See the Semantic Highlighting Guide to read more about semantic highlighting.
contributes.snippets
Contribute snippets for a specific language. The language attribute is the language identifier and the path is the relative path to the snippet file, which defines snippets in the VS Code snippet format.
The example below shows adding snippets for the Go language.
contributes.submenus
Contribute a submenu as a placeholder onto which menu items can be contributed. A submenu requires a label to be shown in the parent menu.
In addition to a title, commands can also define icons that VS Code will show in the editor title menu bar.
submenu example
contributes.taskDefinitions
Contributes and defines an object literal structure that allows to uniquely identify a contributed task in the system. A task definition has at minimum a type property but it usually defines additional properties. For example a task definition for a task representing a script in a package.json file looks like this:
The task definition is defined using JSON schema syntax for the required and properties property. The type property defines the task type. If the above example:
When the extension actually creates a Task, it needs to pass a TaskDefinition that conforms to the task definition contributed in the package.json file. For the npm example a task creation for the test script inside a package.json file looks like this:
contributes.themes
Contribute a color theme to VS Code, defining workbench colors and styles for syntax tokens in the editor.
You must specify a label, whether the theme is a dark theme or a light theme (such that the rest of VS Code changes to match your theme) and the path to the file (JSON format).
theme example
See the Color Theme Guide on how to create a Color Theme.
contributes.typescriptServerPlugins
Contributes TypeScript server plugins that augment VS Code’s JavaScript and TypeScript support:
The above example extension contributes the typescript-styled-plugin which adds styled-component IntelliSense for JavaScript and TypeScript. This plugin will be loaded from the extension and must be installed as a normal NPM dependency in the extension:
Plugin configuration
Extensions can send configuration data to contributed TypeScript plugins through an API provided by VS Code’s built-in TypeScript extension:
The TypeScript server plugin receives the configuration data through an onConfigurationChanged method:
This API allows VS Code extensions to synchronize VS Code settings with a TypeScript server plugin, or dynamically change the behavior of a plugin. Take a look at the TypeScript TSLint plugin and lit-html extensions to see how this API is used in practice.
contributes.views
Contribute a view to VS Code. You must specify an identifier and name for the view. You can contribute to following view containers:
When the user opens the view, VS Code will then emit an activationEvent onView:$
The content of a view can be populated in two ways:
contributes.viewsContainers
Contribute a view container into which Custom views can be contributed. You must specify an identifier, title, and an icon for the view container. At present, you can contribute them to the Activity Bar ( activitybar ) and Panel ( panel ). Below example shows how the Package Explorer view container is contributed to the Activity Bar and how views are contributed to it.
Icon specifications
Size: Icons should be 24×24 and centered.
Color: Icons should use a single color.
Format: It is recommended that icons be in SVG, though any image file type is accepted.
States: All icons inherit the following state styles:
State | Opacity |
---|---|
Default | 60% |
Hover | 100% |
Active | 100% |
contributes.viewsWelcome
Contribute welcome content to Custom views. Welcome content only applies to empty tree views. A view is considered empty if the tree has no children. By convention, any command links that are on a line by themselves are displayed as a button. You can specify the view that the welcome content should apply to with the view property. Visibility of the welcome content can be controlled with the when context value. The text to be displayed as the welcome content is set with the contents property.
Multiple welcome content items can be contributed to one view. When this happens, the content that come from VS Code core comes first, followed by content from built-in extensions, followed by content from all other extensions.
contributes.walkthroughs
Contribute walkthroughs to appear on the Getting Started page. Walkthroughs are automatically opened on install of your extension and provide a convenient way to introduce users to features of your extension.
Walkthroughs consist of a title, description, id, and a series of steps. Additionally, a when condition can be set to hide or show the walkthrough based on context keys. For example, a walkthrough to explain setup on a Linux platform could be given when: «isLinux» to only appear on Linux machines.
Completion events
By default, if no completionEvents events are provided, the step will be checked off when any of it’s buttons are clicked, or if the step has no buttons, when it is opened. If finer control is required, a list of completionEvents can be provided.
Available completion events include:
Once a step has been checked off, it will remain checked off until the user explicitly unchecks the step or resets their progress (via the Getting Started: Reset Progress command).
Vs code settings json
Visual Studio Code Tips and Tricks
«Tips and Tricks» lets you jump right in and learn how to be productive with Visual Studio Code. You’ll become familiar with its powerful editing, code intelligence, and source code control features and learn useful keyboard shortcuts. This topic goes pretty fast and provides a broad overview, so be sure to look at the other in-depth topics in Getting Started and the User Guide to learn more.
If you don’t have Visual Studio Code installed, go to the Download page. You can find platform specific setup instructions at Running VS Code on Linux, macOS, and Windows.
Prefer a video? You can watch a recent Microsoft Build talk Visual Studio Code tips and tricks, which describes 20 tips and tricks for working productively with VS Code.
The best way of exploring VS Code hands-on is to open the Get Started page. You will get an overview of VS Code’s customizations and features. Help > Get Started.
Pick a Walkthrough for a self-guided tour through the setup steps, features, and deeper customizations that VS Code offers. As you discover and learn, the walkthroughs track your progress.
If you are looking to improve your code editing skills open the Interactive Editor Playground. Try out VS Code’s code editing features, like multi-cursor editing, IntelliSense, Snippets, Emmet, and many more. Help > Editor Playground.
Access all available commands based on your current context.
Keyboard Shortcut: kb(workbench.action.showCommands)
Default keyboard shortcuts
All of the commands are in the Command Palette with the associated key binding (if it exists). If you forget a keyboard shortcut, use the Command Palette to help you out.
Keyboard reference sheets
Download the keyboard shortcut reference sheet for your platform (macOS, Windows, Linux).
Quickly open files.
Keyboard Shortcut: kb(workbench.action.quickOpen)
Tip: Type kbstyle(?) to view commands suggestions.
Typing commands such as edt and term followed by a space will bring up dropdown lists.
Navigate between recently opened files
Repeat the Quick Open keyboard shortcut to cycle quickly between recently opened files.
Open multiple files from Quick Open
You can open multiple files from Quick Open by pressing the Right arrow key. This will open the currently selected file in the background and you can continue selecting files from Quick Open.
Navigate between recently opened folders and workspaces
Keyboard Shortcut: kb(workbench.action.openRecent)
Displays a Quick Pick dropdown with the list from File > Open Recent with recently opened folders and workspaces followed by files.
VS Code has a powerful command line interface (CLI) which allows you to customize how the editor is launched to support various scenarios.
Make sure the VS Code binary is on your path so you can simply type ‘code’ to launch VS Code. See the platform specific setup topics if VS Code is added to your environment path during installation (Running VS Code on Linux, macOS, Windows).
Errors and warnings
Keyboard Shortcut: kb(workbench.actions.view.problems)
Quickly jump to errors and warnings in the project.
Cycle through errors with kb(editor.action.marker.nextInFiles) or kb(editor.action.marker.prevInFiles)
You can filter problems either by type (‘errors’, ‘warnings’) or text matching.
Change language mode
Keyboard Shortcut: kb(workbench.action.editor.changeLanguageMode)
If you want to persist the new language mode for that file type, you can use the Configure File Association for command to associate the current file extension with an installed language.
There are many things you can do to customize VS Code.
Change your theme
Keyboard Shortcut: kb(workbench.action.selectTheme)
You can install more themes from the VS Code extension Marketplace.
Additionally, you can install and change your File Icon themes.
Are you used to keyboard shortcuts from another editor? You can install a Keymap extension that brings the keyboard shortcuts from your favorite editor to VS Code. Go to Preferences > Migrate Keyboard Shortcuts from. to see the current list on the Marketplace. Some of the more popular ones:
Customize your keyboard shortcuts
Keyboard Shortcut: kb(workbench.action.openGlobalKeybindings)
You can search for shortcuts and add your own keybindings to the keybindings.json file.
Tune your settings
By default VS Code shows the Settings editor, you can find settings listed below in a search bar, but you can still edit the underlying settings.json file by using the Open Settings (JSON) command or by changing your default settings editor with the workbench.settings.editor setting.
Open User Settings settings.json
Keyboard Shortcut: kb(workbench.action.openSettings)
Change the font size of various UI elements
Change the zoom level
Tip: You will need to have a font installed that supports font ligatures. FiraCode is a popular font on the VS Code team.
You can also toggle Auto Save from the top-level menu with the File > Auto Save.
Format on paste
Change the size of Tab characters
Whitespace characters are rendered by default in text selection.
Ignore files / folders
Removes these files / folders from your editor window.
Remove these files / folders from search results.
Language specific settings
You can scope the settings that you only want for specific languages by the language identifier. You can find a list of commonly used language IDs in the Language Identifiers reference.
Tip: You can also create language specific settings with the Configure Language Specific Settings command.
Add JSON validation
Enabled by default for many file types. Create your own schema and validation in settings.json
or for a schema defined in your workspace
or a custom schema
See more in the JSON documentation.
Keyboard Shortcut: kb(workbench.view.extensions)
In the Extensions view, you can search via the search bar or click the More Actions (. ) button to filter and sort by install count.
In the Extensions view, click Show Recommended Extensions in the More Actions (. ) button menu.
Creating my own extension
Are you interested in creating your own extension? You can learn how to do this in the Extension API documentation, specifically check out the documentation on contribution points.
Files and folders
Keyboard Shortcut: kb(workbench.action.terminal.toggleTerminal)
Keyboard Shortcut: kb(workbench.action.toggleSidebarVisibility)
Keyboard Shortcut: kb(workbench.action.togglePanel)
Keyboard Shortcut: kb(workbench.action.toggleZenMode)
Enter distraction free Zen mode.
Press kbstyle(Esc) twice to exit Zen Mode.
Side by side editing
Keyboard Shortcut: kb(workbench.action.splitEditor)
You can also drag and drop editors to create new editor groups and move editors between groups.
Switch between editors
Move to Explorer window
Keyboard Shortcut: kb(workbench.view.explorer)
Create or open a file
Keyboard Shortcut: kbstyle(Ctrl+click) ( kbstyle(Cmd+click) on macOS)
Close the currently opened folder
Keyboard Shortcut: kb(workbench.action.closeFolder)
Navigate entire history: kb(workbench.action.quickOpenPreviousRecentlyUsedEditorInGroup)
Navigate back: kb(workbench.action.navigateBack)
Navigate forward: kb(workbench.action.navigateForward)
Create language associations for files that aren’t detected correctly. For example, many configuration files with custom file extensions are actually JSON.
Preventing dirty writes
VS Code will show you an error message when you try to save a file that cannot be saved because it has changed on disk. VS Code blocks saving the file to prevent overwriting changes that have been made outside of the editor.
In order to resolve the save conflict, click the Compare action in the error message to open a diff editor that will show you the contents of the file on disk (to the left) compared to the contents in VS Code (on the right):
Use the actions in the editor toolbar to resolve the save conflict. You can either Accept your changes and thereby overwriting any changes on disk, or Revert to the version on disk. Reverting means that your changes will be lost.
Note: The file will remain dirty and cannot be saved until you pick one of the two actions to resolve the conflict.
Here is a selection of common features for editing code. If the keyboard shortcuts aren’t comfortable for you, consider installing a keymap extension for your old editor.
Multi cursor selection
To add cursors at arbitrary positions, select a position with your mouse and use kbstyle(Alt+Click) ( kbstyle(Option+Click) on macOS).
To set cursors above or below the current position use:
Keyboard Shortcut: kb(editor.action.insertCursorAbove) or kb(editor.action.insertCursorBelow)
If you do not want to add all occurrences of the current selection, you can use kb(editor.action.addSelectionToNextFindMatch) instead. This only selects the next occurrence after the one you selected so you can add selections one by one.
Column (box) selection
You can select blocks of text by holding kbstyle(Shift+Alt) ( kbstyle(Shift+Option) on macOS) while you drag your mouse. A separate cursor will be added to the end of each selected line.
You can also use keyboard shortcuts to trigger column selection.
You can add vertical column rulers to the editor with the editor.rulers setting, which takes an array of column character positions where you’d like vertical rulers.
Pressing the kbstyle(Alt) key enables fast scrolling in the editor and Explorers. By default, fast scrolling uses a 5X speed multiplier but you can control the multiplier with the Editor: Fast Scroll Sensitivity ( editor.fastScrollSensitivity ) setting.
Copy line up / down
Keyboard Shortcut: kb(editor.action.copyLinesUpAction) or kb(editor.action.copyLinesDownAction)
The commands Copy Line Up/Down are unbound on Linux because the VS Code default keybindings would conflict with Ubuntu keybindings, see Issue #509. You can still set the commands editor.action.copyLinesUpAction and editor.action.copyLinesDownAction to your own preferred keyboard shortcuts.
Move line up and down
Keyboard Shortcut: kb(editor.action.moveLinesUpAction) or kb(editor.action.moveLinesDownAction)
Shrink / expand selection
Keyboard Shortcut: kb(editor.action.smartSelect.shrink) or kb(editor.action.smartSelect.expand)
You can learn more in the Basic Editing documentation.
Go to Symbol in File
Keyboard Shortcut: kb(workbench.action.gotoSymbol)
Go to Symbol in Workspace
Keyboard Shortcut: kb(workbench.action.showAllSymbols)
The Outline view in the File Explorer (default collapsed at the bottom) shows you the symbols of the currently open file.
You can sort by symbol name, category, and position in the file and allows quick navigation to symbol locations.
Navigate to a specific line
Keyboard Shortcut: kb(workbench.action.gotoLine)
Undo cursor position
Keyboard Shortcut: kb(cursorUndo)
Trim trailing whitespace
Keyboard Shortcut: kb(editor.action.trimTrailingWhitespace)
Transform text commands
You can change selected text to uppercase, lowercase, and title case with the Transform commands from the Command Palette.
Currently selected source code: kb(editor.action.formatSelection)
Whole document format: kb(editor.action.formatDocument)
Keyboard Shortcut: kb(editor.fold) and kb(editor.unfold)
You can also fold/unfold all regions in the editor with Fold All ( kb(editor.foldAll) ) and Unfold All ( kb(editor.unfoldAll) ).
You can fold all block comments with Fold All Block Comments ( kb(editor.foldAllBlockComments) ).
Select current line
Keyboard Shortcut: kb(expandLineSelection)
Navigate to beginning and end of file
Keyboard Shortcut: kb(cursorTop) and kb(cursorBottom)
Open Markdown preview
In a Markdown file, use
Keyboard Shortcut: kb(markdown.showPreview)
Side by side Markdown edit and preview
In a Markdown file, use
Keyboard Shortcut: kb(markdown.showPreviewToSide)
The preview and editor will synchronize with your scrolling in either view.
kb(editor.action.triggerSuggest) to trigger the Suggestions widget.
You can view available methods, parameter hints, short documentation, etc.
Go to Definition
You can also see the type definition if you press kbstyle(Ctrl) ( kbstyle(Cmd) on macOS) when you are hovering over the type.
Go to References
Find All References view
Select a symbol then type kb(references-view.findReferences) to open the References view showing all your file’s symbols in a dedicated view.
Search and modify
Install the ESLint extension. Configure your linter however you’d like. Consult the ESLint specification for details on its linting rules and options.
Here is configuration to use ES6.
See IntelliSense for your package.json file.
Create custom snippets
File > Preferences > User Snippets (Code > Preferences > User Snippets on macOS), select the language, and create a snippet.
Keyboard Shortcut: kb(workbench.view.scm)
Git integration comes with VS Code «out-of-the-box». You can install other SCM providers from the Extension Marketplace. This section describes the Git integration but much of the UI and gestures are shared by other SCM providers.
From the Source Control view, select a file to open the diff.
Alternatively, click the Open Changes button in the top right corner to diff the current open file.
Views
The default view for diffs is the side by side view.
Toggle inline view by clicking the More Actions (. ) button in the top right and selecting Toggle Inline View.
Review pane
Edit pending changes
You can make edits directly in the pending changes of the diff view.
Easily switch between Git branches via the Status Bar.
Stage file changes
Hover over the number of files and click the plus button.
Click the minus button to unstage changes.
Stage selected
Stage a portion of a file by selecting that file (using the arrows) and then choosing Stage Selected Ranges from the Command Palette.
Undo last commit
Click the (. ) button and then select Undo Last Commit to undo the previous commit. The changes are added to the Staged Changes section.
VS Code makes it easy to see what Git commands are actually running. This is helpful when learning Git or debugging a difficult source control issue.
Use the Toggle Output command ( kb(workbench.action.output.toggleOutput) ) and select Git in the dropdown.
View diff decorations in editor. See documentation for more details.
Resolve merge conflicts
During a merge, go to the Source Control view ( kb(workbench.view.scm) ) and make changes in the diff view.
You can resolve merge conflicts with the inline CodeLens which lets you Accept Current Change, Accept Incoming Change, Accept Both Changes, and Compare Changes.
Set VS Code as default merge tool
Set VS Code as default diff tool
From the Run and Debug view ( kb(workbench.view.debug) ), select create a launch.json file, which will prompt you to select the environment that matches your project (Node.js, Python, C++, etc). This will generate a launch.json file. Node.js support is built-in and other environments require installing the appropriate language extensions. See the debugging documentation for more details.
Breakpoints and stepping through
Place breakpoints next to the line number. Navigate forward with the Debug widget.
Inspect variables in the Run panels and in the console.
Logpoints act much like breakpoints but instead of halting the debugger when they are hit, they log a message to the console. Logpoints are especially useful for injecting logging while debugging production servers that cannot be modified or paused.
Add a logpoint with the Add Logpoint command in the left editor gutter and it will be displayed as a «diamond» shaped icon. Log messages are plain text but can include expressions to be evaluated within curly braces (‘<>‘).
Auto detect tasks
Select Terminal from the top-level menu, run the command Configure Tasks, then select the type of task you’d like to run. This will generate a tasks.json file with content like the following. See the Tasks documentation for more details.
There are occasionally issues with auto generation. Check out the documentation for getting things to work properly.
Run tasks from the Terminal menu
Select Terminal from the top-level menu, run the command Run Task, and select the task you want to run. Terminate the running task by running the command Terminate Task
Define keyboard shortcuts for tasks
For example, to bind kbstyle(Ctrl+H) to the Run tests task, add the following:
Run npm scripts as tasks from the Explorer
VS Code has a Portable mode which lets you keep settings and data in the same location as your installation, for example, on a USB drive.
The Visual Studio Code team uses the Insiders version to test the latest features and bug fixes of VS Code. You can also use the Insiders version by downloading it here.
Customize build and debug tasks for «Open Folder» development
Visual Studio knows how to run many different languages and codebases, but it doesn’t know how to run everything. If you opened a code folder in Visual Studio, and Visual Studio knows how to run your code, you can run it right away without any additional configuration.
If the codebase uses custom build tools that Visual Studio doesn’t recognize, you need to provide some configuration details to run and debug the code in Visual Studio. You instruct Visual Studio how to build your code by defining build tasks. You can create one or more build tasks to specify all the items a language needs to build and run its code. You can also create arbitrary tasks that can do nearly anything you want. For example, you can create a task to list the contents of a folder or to rename a file.
Customize your project-less codebase by using the following .json files:
File name | Purpose |
---|---|
tasks.vs.json | Specify custom build commands and compiler switches, and arbitrary (non-build related) tasks. Accessed via the Solution Explorer right-click menu item Configure Tasks. |
launch.vs.json | Specify command-line arguments for debugging. Accessed via the Solution Explorer right-click menu item Debug and Launch Settings. |
These .json files are located in a hidden folder called .vs in the root folder of your codebase. The tasks.vs.json and launch.vs.json files are created by Visual Studio on an as-needed basis when you choose either Configure Tasks or Debug and Launch Settings on a file or folder in Solution Explorer. These .json files are hidden because users generally don’t want to check them into source control. However, if you want to be able to check them into source control, drag the files into the root of your codebase by using your file system, where they then are visible in Solution Explorer and to source control.
To view hidden files in Visual Studio, choose the Show All Files button on the Solution Explorer toolbar.
Define tasks with tasks.vs.json
You can automate build scripts or any other external operations on the files you have in your current workspace by running them as tasks directly in the IDE. You can configure a new task by right-clicking on a file or folder and selecting Configure Tasks.
This creates (or opens) the tasks.vs.json file in the .vs folder. You can define a build task or arbitrary task in this file, and then invoke it using the name you gave it from the Solution Explorer right-click menu.
Custom tasks can be added to individual files, or to all files of a specific type. For instance, NuGet package files can be configured to have a «Restore Packages» task, or all source files can be configured to have a static analysis task, such as a linter for all .js files.
Define custom build tasks
If your codebase uses custom build tools that Visual Studio doesn’t recognize, then you cannot run and debug the code in Visual Studio until you complete some configuration steps. Visual Studio provides build tasks where you can tell Visual Studio how to build, rebuild, and clean your code. The tasks.vs.json build task file couples the Visual Studio inner development loop to the custom build tools used by your codebase.
Consider a codebase that consists of a single C# file called hello.cs. The makefile for such a codebase might look like this:
For such a makefile that contains build, clean, and rebuild targets, you can define the following tasks.vs.json file. It contains three build tasks for building, rebuilding, and cleaning the codebase, using NMAKE as the build tool.
After you define build tasks in tasks.vs.json, additional right-click menu (context menu) items are added to the corresponding files in Solution Explorer. For this example, «build», «rebuild», and «clean» options are added to the context menu of any makefile files.
The commands appear in the context menu under the Configure Tasks command due to their contextType settings. «build», «rebuild», and «clean» are build commands, so they appear in the build section in the middle of the context menu.
When you select one of these options, the task executes. Output appears in the Output window, and build errors appear in the Error List.
Define arbitrary tasks
You can define arbitrary tasks in the tasks.vs.json file, to do just about anything you want. For example, you can define a task to display the name of the currently selected file in the Output window, or to list the files in a specified directory.
The following example shows a tasks.vs.json file that defines a single task. When invoked, the task displays the filename of the currently selected .js file.
After saving tasks.vs.json, you can right-click on any .js file in the folder and choose Echo filename. The file name is displayed in the Output window.
If your codebase doesn’t contain a tasks.vs.json file, you can create one by choosing Configure Tasks from the right-click or context menu of a file in Solution Explorer.
The next example defines a task that lists the files and subfolders of the bin directory.
This task applies to all files. When you open the context menu on any file in Solution Explorer, the task’s name List Outputs appears at the bottom of the menu. When you choose List Outputs, the contents of the bin directory are listed in the Output window in Visual Studio.
Settings scope
Multiple tasks.vs.json files can exist at the root and subdirectories of a codebase. This design enables the flexibility to have different behavior in different subdirectories of the codebase. Visual Studio aggregates or overrides settings throughout the codebase, prioritizing files in the following order:
These aggregation rules apply to tasks.vs.json. For information on how settings in other file are aggregated, see the corresponding section for that file in this article.
Properties for tasks.vs.json
This section describes some of the properties you can specify in tasks.vs.json.
appliesTo
File mask | Description |
---|---|
«*» | task is available to all files and folders in the workspace |
«*/» | task is available to all folders in the workspace |
«*.js» | task is available to all files with the extension .js in the workspace |
«/*.js» | task is available to all files with the extension .js in the root of the workspace |
«src/*/» | task is available to all subfolders of the src folder |
«makefile» | task is available to all makefile files in the workspace |
«/makefile» | task is available only to the makefile in the root of the workspace |
Macros for tasks.vs.json
Configure debugging with launch.vs.json
To configure CMake projects for debugging, see Configure CMake debugging sessions.
To configure your codebase for debugging, in Solution Explorer choose the Debug and Launch Settings menu item from the right-click or context menu of your executable file.
In the Select a Debugger dialog box, choose an option, and then choose the Select button.
If the launch.vs.json file doesn’t already exist, it is created.
Next, right-click on the executable file in Solution Explorer, and choose Set as Startup Item.
The executable is designated as the startup item for your codebase, and the debugging Start button’s title changes to reflect the name of your executable.
When you choose F5, the debugger launches and stops at any breakpoint you may have already set. All the familiar debugger windows are available and functional.
For additional details about custom build and debug tasks in C++ open folder projects, see Open Folder support for C++ build systems in Visual Studio.
Specify arguments for debugging
You can specify command-line arguments to pass in for debugging in the launch.vs.json file. Add the arguments in the args array, as shown in the following example:
When you save this file, the name of the new configuration appears in the debug target drop-down list, and you can select it to start the debugger. You can create as many debug configurations as you like.
The configurations array property in launch.vs.json is read from two file locations—the root directory for the codebase, and the .vs directory. If there is a conflict, priority is given to the value in .vs\launch.vs.json.
Additional settings files
In addition to the three .json files described in this topic, Visual Studio also reads settings from some additional files, if they exist in your codebase.
.vscode\settings.json
You can have any number of .vscode\settings.json files in your codebase. Settings read from this file are applied to the parent directory of .vscode and all of its subdirectories.
.gitignore
.gitignore files are used to tell Git which files to ignore; that is, which files and directories you don’t want to check in. .gitignore files are usually included as part of a codebase so that the settings can be shared with all developers of the codebase. Visual Studio reads patterns in .gitignore files to filter items visually and from some search tools.
Settings read from the .gitignore file are applied to its parent directory and all subdirectories.
Cannot Edit Default VSCode JSON Settings
I am using VSCode 1.47.3 on Windows 10. I cannot edit default settings in json:
I’ve tried opening VSCode as admin, uninstalling and reinstalling, restarting my computer, and downgrading to 1.46, but still cannot edit. Does someone know how to fix this?
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The default settings in vscode is a non-editable document. It acts as a way for you to view the default settings for native settings as well as extension default settings.
These defaults are also used to identify when a setting has changed with a ‘blue’ line indicator, when using the settings editor:
Changes to settings are reloaded by VS Code as you change them. Modified settings are now indicated with a blue line similar to modified lines in the editor. The gear icon opens a context menu with options to reset the setting to its default value as well as copy setting as JSON.
Currently, vscode only offers 2 editable settings:
VS Code provides two different scopes for settings:
Workspace settings override user settings. Workspace settings are specific to a project and can be shared across developers on a project.
You can configure these settings with the settings editor, as pictured above, or you can navigate to their JSON counterparts for manual entry (example pictured on the right below).
By default, VS Code shows the Settings editor, but you can still edit the underlying settings.json file by using the Open Settings (JSON) command from your command palette or by changing your default settings editor with the workbench.settings.editor setting.
Settings
You can define which view is shown using the following settings:
Opens the default settings any time you open regular settings (this only works with the JSON settings editor option)
Determine which editor to use, you can elect UI or JSON
Где находится файл настроек по умолчанию VSCode?
Water Cooler v2
Список настроек по умолчанию не хранится в одном файле: он создается по запросу.
(Имеет смысл генерировать его каждый раз, когда пользователь запрашивает его, потому что он мог измениться с момента последнего запроса пользователя, потому что расширение могло быть установлено или удалено: список включает параметры, специфичные для расширения.)
Возможно, причина вашего запроса заключается в том, что вам нужен способ просмотра списка без разделения редактора. (Это была причина, по которой я сделал поиск в Интернете, который привел меня к этой странице.) Этого можно добиться, выполнив команду «Предпочтения: Открыть настройки по умолчанию (JSON)».
Все значения по умолчанию в формате только для чтения
Если вы просто хотите увидеть все значения по умолчанию, используйте палитру команд (Ctrl + Shift + P) и запустите «Предпочтения: открыть настройки по умолчанию (JSON)». VSCode сгенерирует описание всех значений по умолчанию в формате JSON.
Откуда берутся значения по умолчанию
Подробности
Давайте посмотрим на несколько примеров. Когда я открываю настройки, я вижу длинный список, и это вверху:
Опять же, значение по умолчанию 1000 в графическом интерфейсе пользователя происходит от атрибута default здесь.
И снова интересно, что значение по умолчанию зависит от платформы. Поскольку я не работаю на Mac, я вижу значение по умолчанию 14.
И так далее. Каждая из настроек по умолчанию берется из исходного кода Typescript или, в некоторых случаях, файлов package.json для расширений (встроенных или установленных пользователем).
@Timo В моем первоначальном ответе предполагалось, что целью было модифицировать по умолчанию, но вы правы, что можно Посмотреть все из них, не копаясь в источниках. Я обновил свой ответ, чтобы объяснить это.
@Timo Насколько я могу судить, создаваемое им содержимое существует только в памяти. Конечно, вы можете сохранить файл на диск (с помощью «Файл», «Сохранить как»).
This seems to imply that the folder should contain project-specific settings and thus be included in source. Also, this post on UserVoice seems to imply some typings would go in there, also suggesting that it should be committed.
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Examples of settings to include:
Other Factors
For example, if IDE setting files have absolute paths to the repo or any files/libraries, etc., then that is bad, don’t share. But if all the references are relative, then they should work for anyone using the repo (although, be careful about path specification differences between Windows/Unix..).
About User, Workspace, and Folder settings
So, you should generally put custom settings for your personal PC into the user settings, and put generic settings into the workspace or folder settings.
I can’t find python json settings in vs code
I’m trying to edit python json settings to edit font size and stuff like that but whenever I open settings.json it opens something else
1 Answer 1
Just copy «editor.fontSize»: 24 into your setting.json at the end for set the font-size to 24.
More about settings.json in Visual Studio Code, you can read here.
Not the answer you’re looking for? Browse other questions tagged python visual-studio-code vscode-settings or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How do I back up my VS Code settings and list of installed extensions?
I’ve just been through the VS Code installation process twice. The initial install is quick and painless (as is the editor itself), but I have had to remember the list of extensions I installed and am installing new ones a great rate.
With Sublime Text, I’d just copy a settings file to another PC and could auto-install any workflow dependencies that way, but what is the approach with VS Code?
Can I just back up a JSON ‘settings’ file or similar so that I can easily re-create my working environment (complete with extensions)?
5 Answers 5
That should show you a list of the extensions
I’ve also had success using Visual Studio Code Settings Sync Extension to sync settings to GitHub gist
EDIT: In the lastest release of VSCode (May 2016) it is now possible to list the installed extension in the command line
So as treehead’s edit or MarkP’s answer showed you can now list all extensions installed so the way to install that list of extensions would be to:
Transfer the newly created file to the machine that you want to install those extensions to. On that machine you would:
Which will then go through each extension in that file and install the extension.
If you want a clean install (AKA remove all existing extensions on that machine) you could run this before you install the new extensions (otherwise you will remove those new extensions too). BE CAREFUL as this will remove all extensions in VS Code:
Here’s the location of the VSCode settings (see below + comments):
It appears to only be storing modified settings, which is really nice (so you don’t clobber up or screw with future versions).
You may also want /snippets/, in the same folder as settings.json.
Vs code settings json
At its heart, Visual Studio Code is a code editor. Like many other code editors, VS Code adopts a common user interface and layout of an explorer on the left, showing all of the files and folders you have access to, and an editor on the right, showing the content of the files you have opened.
VS Code comes with a simple and intuitive layout that maximizes the space provided for the editor while leaving ample room to browse and access the full context of your folder or project. The UI is divided into five areas:
Each time you start VS Code, it opens up in the same state it was in when you last closed it. The folder, layout, and opened files are preserved.
Open files in each editor are displayed with tabbed headers (Tabs) at the top of the editor region. To learn more about tabbed headers, see the Tabs section below.
Tip: You can move the Side Bar to the right hand side (View > Move Side Bar Right) or toggle its visibility ( kb(workbench.action.toggleSidebarVisibility) ).
Side by side editing
You can open as many editors as you like side by side vertically and horizontally. If you already have one editor open, there are multiple ways of opening another editor to the side of the existing one:
Whenever you open another file, the editor that is active will display the content of that file. So if you have two editors side by side and you want to open file ‘foo.cs’ into the right-hand editor, make sure that editor is active (by clicking inside it) before opening file ‘foo.cs’.
By default editors will open to the right-hand side of the active one. You can change this behavior through the setting workbench.editor.openSideBySideDirection and configure to open new editors to the bottom of the active one instead.
Tip: You can resize editors and reorder them. Drag and drop the editor title area to reposition or resize the editor.
A Minimap (code outline) gives you a high-level overview of your source code, which is useful for quick navigation and code understanding. A file’s minimap is shown on the right side of the editor. You can click or drag the shaded area to quickly jump to different sections of your file.
Tip: You can move the minimap to the left hand side or disable it completely by respectively setting «editor.minimap.side»: «left» or «editor.minimap.enabled»: false in your user or workspace settings.
The image above also shows indentation guides (vertical lines) which help you quickly see matching indent levels. If you would like to disable indent guides, you can set «editor.guides.indentation»: false in your user or workspace settings.
The editor has a navigation bar above its contents called Breadcrumbs. It shows the current location and allows you to quickly navigate between folders, files, and symbols.
Breadcrumbs always show the file path and if the current file type has language support for symbols, the symbol path up to the cursor position. You can disable breadcrumbs with the View > Show Breadcrumbs toggle command. For more information about the breadcrumbs feature, such as how to customize their appearance, see the Breadcrumbs section of the Code Navigation article.
After opening a folder in VS Code, the contents of the folder are shown in the Explorer. You can do many things from here:
Tip: You can drag and drop files into the Explorer from outside VS Code to copy them (if the explorer is empty VS Code will open them instead)
VS Code works very well with other tools that you might use, especially command-line tools. If you want to run a command-line tool in the context of the folder you currently have open in VS Code, right-click the folder and select Open in Command Prompt (or Open in Terminal on macOS or Linux).
You can also navigate to the location of a file or folder in the native Explorer by right-clicking on a file or folder and selecting Reveal in Explorer (or Reveal in Finder on macOS or Open Containing Folder on Linux).
Tip: Type kb(workbench.action.quickOpen) (Quick Open) to quickly search and open a file by its name.
You can select multiple files in the File Explorer and OPEN EDITORS view to run actions (Delete, Drag and Drop, Open to the Side) on multiple items. Use the Ctrl/Cmd key with click to select individual files and Shift + click to select a range. If you select two items, you can now use the context menu Compare Selected command to quickly diff two files.
Note: In earlier VS Code releases, clicking with the Ctrl/Cmd key pressed would open a file in a new Editor Group to the side. If you would still like this behavior, you can use the workbench.list.multiSelectModifier setting to change multi-selection to use the Alt key.
Advanced tree navigation
You can filter the currently visible files in the File Explorer. With the focus on the File Explorer, press kbstyle(Ctrl/Cmd+F) to open the tree Find control and type part of the file name you want to match. You will see a Find control in the top-right of the File Explorer showing what you have typed and matching file names will be highlighted. Pressing the Filter button will toggle between the two modes: highlighting and filtering. Pressing kbstyle(DownArrow) will let you focus the first matched element and jump between matching elements.
This navigation feature is available for all tree views in VS Code, so feel free to try it out in other areas of the product.
The Outline view is a separate section in the bottom of the File Explorer. When expanded, it will show the symbol tree of the currently active editor.
The Outline view has different Sort By modes, optional cursor tracking, and supports the usual open gestures. It also includes an input box which finds or filters symbols as you type. Errors and warnings are also shown in the Outline view, letting you see at a glance a problem’s location.
For symbols, the view relies on information computed by your installed extensions for different file types. For example, the built-in Markdown support returns the Markdown header hierarchy for a Markdown file’s symbols.
There are several Outline view settings which allow you to enable/disable icons and control the errors and warnings display (all enabled by default):
At the top of the Explorer is a view labeled OPEN EDITORS. This is a list of active files or previews. These are files you previously opened in VS Code that you were working on. For example, a file will be listed in the OPEN EDITORS view if you:
Just click an item in the OPEN EDITORS view, and it becomes active in VS Code.
Once you are done with your task, you can remove files individually from the OPEN EDITORS view, or you can remove all files by using the View: Close All Editors or View: Close All Editors in Group actions.
The File Explorer is just one of the Views available in VS Code. There are also Views for:
Tip: You can open any view using the View: Open View command.
You can show or hide views from within the main view and also reorder them by drag and drop.
The Activity Bar on the left lets you quickly switch between Views. You can also reorder Views by dragging and dropping them on the Activity Bar or remove a View entirely (right click Hide from Activity Bar).
The Command Palette provides access to many commands. You can execute editor commands, open files, search for symbols, and see a quick outline of a file, all using the same interactive window. Here are a few tips:
Configuring the editor
VS Code gives you many options to configure the editor. From the View menu, you can hide or toggle various parts of the user interface, such as the Side Bar, Status Bar, and Activity Bar.
Hide the Menu Bar (Windows, Linux)
Most editor configurations are kept in settings which can be modified directly. You can set options globally through user settings or per project/folder through workspace settings. Settings values are kept in a settings.json file.
Note for macOS users: The Preferences menu is under Code not File. For example, Code > Preferences > Settings.
You will see the VS Code Default Settings in the left window and your editable settings.json on the right. You can easily filter settings in the Default Settings using the search box at the top. Copy a setting over to the editable settings.json on the right by clicking on the edit icon to the left of the setting. Settings with a fixed set of values allow you to pick a value as part of their edit icon menu.
After editing your settings, type kb(workbench.action.files.save) to save your changes. The changes will take effect immediately.
Note: Workspace settings will override User settings and are useful for sharing project specific settings across a team.
Centered editor layout
Centered editor layout allows you to center align the editor area. This is particularly useful when working with a single editor on a large monitor. You can use the sashes on the side to resize the view (hold down the Alt key to independently move the sashes).
Visual Studio Code shows open items with Tabs (tabbed headings) in the title area above the editor.
When you open a file, a new Tab is added for that file.
Tabs let you quickly navigate between items and you can Drag and Drop Tabs to reorder them.
If you don’t want to use Tabs, you can disable the feature by setting the workbench.editor.showTabs setting to false:
See the section below to optimize VS Code when working without Tabs.
By default, new Tabs are added to the right of the existing Tabs but you can control where you’d like new Tabs to appear with the workbench.editor.openPositioning setting.
For example, you might like new tabbed items to appear on the left:
When you single-click or select a file in the Explorer, it is shown in a preview mode and reuses an existing Tab. This is useful if you are quickly browsing files and don’t want every visited file to have its own Tab. When you start editing the file or use double-click to open the file from the Explorer, a new Tab is dedicated to that file.
Preview mode is indicated by italics in the Tab heading:
If you’d prefer to not use preview mode and always create a new Tab, you can control the behavior with these settings:
When you split an editor (using the Split Editor or Open to the Side commands), a new editor region is created which can hold a group of items. You can open as many editor regions as you like side by side vertically and horizontally.
You can see these clearly in the OPEN EDITORS section at the top of the Explorer view:
You can Drag and Drop editor groups on the workbench, move individual Tabs between groups and quickly close entire groups (Close All).
Note: VS Code uses editor groups whether or not you have enabled Tabs. Without Tabs, editor groups are a stack of your open items with the most recently selected item visible in the editor pane.
Grid editor layout
By default, editor groups are laid out in vertical columns (for example when you split an editor to open it to the side). You can easily arrange editor groups in any layout you like, both vertically and horizontally:
To support flexible layouts, you can create empty editor groups. By default, closing the last editor of an editor group will also close the group itself, but you can change this behavior with the new setting workbench.editor.closeEmptyGroups: false :
There are a predefined set of editor layouts in the new View > Editor Layout menu:
There are many keyboard commands for adjusting the editor layout with the keyboard alone, but if you prefer to use the mouse, drag and drop is a fast way to split the editor into any direction:
Pro Tip: If you press and hold the Alt key while hovering over the toolbar action to split an editor, it will offer to split to the other orientation. This is a fast way to split either to the right or to the bottom.
Here are some handy keyboard shortcuts to quickly navigate between editors and editor groups.
If you’d like to modify the default keyboard shortcuts, see Key Bindings for details.
Working without Tabs
If you prefer not to use Tabs (tabbed headings), you can disable Tabs (tabbed headings) entirely by setting workbench.editor.showTabs to false.
Disable Preview mode
Without Tabs, the OPEN EDITORS section of the File Explorer is a quick way to do file navigation. With preview editor mode, files are not added to the OPEN EDITOR list nor editor group on single-click open. You can disable this feature through the workbench.editor.enablePreview and workbench.editor.enablePreviewFromQuickOpen settings.
Ctrl+Tab to navigate in entire editor history
You can change keybindings for kbstyle(Ctrl+Tab) to show you a list of all opened editors from the history independent from the active editor group.
Edit your keybindings and add the following:
Close an entire group instead of a single editor
If you liked the behavior of VS Code closing an entire group when closing one editor, you can bind the following in your keybindings.
VS Code has some options to control how windows (instances) should be opened or restored between sessions.
The window.restoreWindows setting tells VS Code how to restore the opened windows of your previous session. By default, VS Code will restore all windows you worked on during your previous session (setting: all ). Change this setting to none to never reopen any windows and always start with an empty VS Code instance. Change it to one to reopen the last opened window you worked on or folders to only restore windows that had folders opened.
Now that you know the overall layout of VS Code, start to customize the editor to how you like to work by looking at the following topics:
How can I change the color of the indent guides?
The indent guide colors are customizable as are most VS Code UI elements. To customize the indent guides color for your active color theme, use the workbench.colorCustomizations setting and modify the editorIndentGuide.background value.
For example, to make the indent guides bright blue, add the following to your settings.json :
Can I hide the OPEN EDITORS section in the Explorer?
VS Code: отображение пробелов, settings.json, keybindings.json
Да, и я не берусь утверждать, какая из этих двух групп работает эффективнее. То есть я не утверждаю, что аккуратисты чем-то лучше разгильдяев в данном случае или наоборот. С одной стороны, аккуратно отформатированный код удобнее читать. С другой стороны, красивое форматирование кода можно возложить на разнообразные программы, которые сейчас существуют. В принципе логично, если работа по красивому форматированию кода будет выполняться автоматически программами, а не программистами.
Одна из вещей, которая нужна аккуратистам в текстовом редакторе — это включение/отключение отображения пробелов. В текстовом редакторе «VS Code» есть функционал для включения/отключения отображения пробелов. Но, на мой взгляд, он требует некоторой донастройки.
Включить/отключить отображение пробелов в этом редакторе можно из главного меню «Вид – Отображать пробелы». Этот пункт меню является переключателем: каждый выбор этого пункта переключает редактор на один из двух режимов: отображать пробелы, не отображать пробелы. Если слева от этого пункта стоит галка, это значит, что включен режим «отображать пробелы». Если слева от этого пункта нет галки, значит, что включен режим «не отображать пробелы». Иллюстрация (здесь видна только нижняя часть выпадающего из пункта «Вид» меню):
Замечание. Иногда при включенном режиме «отображать пробелы» они таки не отображаются. Это известная ошибка в этом редакторе. Лечится выключением/включением этого пункта меню.
Вот как выглядит по умолчанию работа в редакторе «VS Code» с включенным режимом «отображать пробелы»:
Пробелы отображаются серенькими точками. Но с таким цветом их плохо видно. Такой цвет точек подходит, если постоянно работать в режиме «отображать пробелы»: с одной стороны точки всё-таки видно, с другой стороны они не слишком мозолят глаза. Я же привык в основном работать при выключенном режиме «отображать пробелы», включая его при необходимости, когда нужно понять, сколько и где введено пробелов. При таком способе работы хочется, чтобы точки отображались цветом поярче, поконтрастнее, ведь я их буду включать на небольшое время.
В редакторе «VS Code» предусмотрен способ настроить желаемый цвет точек, изображающих пробелы при включенном режиме «отображать пробелы».
Параметры: «workbench color customizations»
Для изменения этой настройки следует открыть страницу «Параметры». Открыть ее можно из главного меню «Файл – Настройки – Параметры». Также можно использовать сочетание клавиш «Ctrl+,» (клавиша «Ctrl» и клавиша «,» [запятая, которая ближе к клавише пробела]).
В редакторе «VS Code» настолько много параметров, что их, как я понимаю, физически не получается засунуть в привычные окна с параметрами. Поэтому страница «Параметры» содержит параметры в виде огромного списка. Просто так искать в этом списке нужную настройку не получится — займет слишком много времени. Поэтому я сначала нашел название нужной настройки в интернетах, а потом ввел это название в строку поиска параметра на странице «Параметры».
Для нахождения нужной настройки следует начать вводить в строке поиска параметра следующий текст: «workbench color customizations» (по-русски «настройки цветов на рабочем месте»). После этого редактор отобразит (отфильтрует из списка) только настройки, названия которых похожи на введенный текст. В данном случае будет только одна нужная нам настройка. Рядом с нею есть надпись-ссылка «Изменить в settings.json». Пользовательские настройки редактора «VS Code» хранятся в этом текстовом файле. Нажав на эту ссылку, мы откроем этот файл для редактирования в редакторе «VS Code». Причем редактор поместит курсор именно в то место этого файла, где нужно добавить новую настройку. Вот как это выглядит у меня:
На вышеприведенной иллюстрации видно, что файл с пользовательскими настройками у меня на компьютере программа «VS Code» поместила в следующем местоположении:
Для указания нужного цвета точек, изображающих пробелы, я изменил этот файл так:
После окончания внесения нужных изменений файл «settings.json» следует сохранить («Ctrl+S»). После сохранения его можно закрыть («Ctrl+F4»). Страницу «Параметры» тоже можно закрыть («Ctrl+F4»).
Вот как теперь (после вышеуказанной донастройки) у меня выглядит работа в редакторе «VS Code» с включенным режимом «отображать пробелы»:
Для точек выбрал оранжевый цвет, потому что привык к нему в текстовом редакторе «Notepad++».
Привязка сочетания клавиш
Напомню, что в редакторе «VS Code» нет панели инструментов, об этом у меня был отдельный пост. Можно было бы поместить кнопку переключения режима «отображать пробелы»/«не отображать пробелы» в панель инструментов, как это сделано в текстовом редакторе «Notepad++». В редакторе «VS Code» за неимением панели инструментов удобно было бы переключать этот режим с помощью какого-нибудь сочетания клавиш, но по умолчанию к переключению этого режима никакого сочетания клавиш не привязано.
В редакторе «VS Code» можно к какому-либо действию привязать желаемое сочетание клавиш. По-английски это называется «key bindings». Пользовательские привязки сочетаний клавиш к каким-либо действиям сохраняются в файле «keybindings.json». На моем компьютере программа «VS Code» хранит этот файл в следующем местоположении:
Необязательно напрямую редактировать этот файл. Нужную привязку можно назначить из окна редактора «VS Code». Список привязок сочетаний клавиш к действиям можно открыть из главного меню «Файл – Настройки — Сочетания клавиш» («Ctrl+K Ctrl+S»).
Также, как и в случае параметров, привязок сочетаний клавиш в редакторе «VS Code» огромное количество. Поэтому нет смысла вручную искать в списке нужную строку. Следует воспользоваться строкой поиска нужного действия для назначения привязки. Можно начать набирать в строке поиска следующий текст: «toggle render whitespace» (по-русски «переключение отображения пробелов»). Программа «VS Code» отфильтрует список привязок и останется один нужный пункт.
Для начала добавления нужного сочетания клавиш следует дважды щелкнуть мышкой по этому пункту (или один раз щелкнуть мышкой на знак плюса слева от этого пункта). После этого откроется дополнительное окно, в котором следует ввести желаемое сочетание клавиш. Если введенное сочетание клавиш уже используется для какого-либо действия, то программа «VS Code» сообщит об этом. Очевидно, что следует найти такое сочетание клавиш, которое не используется для других действий. Я пока что выбрал сочетание клавиш «Alt+X», просто потому, что оно находится рядом с сочетанием клавиш «Alt+Z» (включение/выключение переноса строк).
После выбора и ввода желаемого сочетания клавиш следует нажать клавишу «Enter» и указанное сочетание клавиш будет привязано к указанному действию. После этого страницу «Сочетания клавиш» можно закрыть («Ctrl+F4»).
Вот как теперь выглядит содержимое вышеуказанного файла «keybindings.json»:
Вот как теперь выглядит нижняя часть меню, выпадающего из главного меню «Вид»:
На вышеприведенной иллюстрации видно, что справа отпункта «Отображать пробелы» появилось сочетание клавиш «Alt+X».
С помощью этого сочетания клавиш я теперь в любой момент могу быстро переключиться между режимом с отображением пробелов и режимом без отображения пробелов.
Advanced Visual Studio Code for Python Developers
Table of Contents
Visual Studio Code, or VS Code for short, is a free and open source code editor by Microsoft. You can use VS Code as a lightweight code editor to make quick changes, or you can configure it as an integrated development environment (IDE) through the use of third-party extensions. In this tutorial, you’re going to look at how to get the most out of VS Code for Python development.
During this tutorial, you’ll learn how you can configure, extend, and optimize VS Code for a more effective and productive Python development environment. After finishing this tutorial, you’ll have a variety of tools to help you be more productive using VS Code. It can be a powerful tool for rapid Python development.
In this tutorial, you’ll learn how to:
As usual, this tutorial is full of links, tips, and tricks to help you on your way.
If you haven’t already installed Visual Studio Code or the Python extension, you’ll need both for this tutorial. If you’re just getting started with VS Code, you might want to check out Jon Fincher’s tutorial on Python development in Visual Studio Code before continuing with this one.
Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.
Mastering the Visual Studio Code User Interface
By default, VS Code’s user interface is designed for everyone—whether you’re writing C++, doing front-end development with JavaScript and CSS, or using data science tools like Jupyter Notebooks. In this first section, you’ll explore how to tailor VS Code to support how you work.
Keyboard Shortcuts
For almost everything that you do in VS Code, you can do it directly from the keyboard. You can map all activities in VS Code, whether they’re built-in or provided via extensions, to a keyboard shortcut.
A small subset of built-in commands is already mapped in Keyboard Shortcuts. If you want to learn these default shortcuts, print out the PDF for Windows, macOS, or Linux and pin it next to your monitor.
As a Python developer, a lot of the commands you’ll use in Visual Studio Code are provided from extensions, similar to the Python extension that you already installed. These don’t come with shortcuts mapped by default, but you can configure them using VS Code’s Keyboard Shortcuts editor.
Using the Keyboard Shortcuts Editor
Open the Keyboard Shortcuts editor by going to File → Preferences → Keyboard Shortcuts or Code → Preferences → Keyboard Shortcuts on macOS:
In this editor, you can see a list of all the existing shortcuts along with their details:
To override an existing binding, right-click on the existing action and click Change Keybinding. To assign a keybinding to a command that has no binding, double-click on it. If the key sequence you press is already assigned to something else, VS Code will warn you with a link to see which commands are mapped to this keybinding.
To assign that shortcut to only work when you’re editing Python code, right-click on the shortcut and select Change When Expression. Enter the expression editorLangId == ‘python’ :
There are more conditional operators to choose from if you need something more specific. Here are some examples to get you started:
Once you’ve configured this extension, open up a Python file in the editor to try it out by pressing your newly assigned keyboard shortcut Ctrl + Alt + T to open up a Python terminal.
Setting Up Keyboard Shortcuts for Commands From the Command Palette
You’ll refer to the Command Palette many times in this tutorial. Most of the functionality in VS Code is accessible through the UI from context menus, but you won’t find everything there. Anything that can be done in the core editor or via an extension is available in the Command Palette. You can get to the Command Palette by pressing one of these keyboard shortcuts:
Once you’ve started using the Command Palette regularly, you may find that there are five to ten commands you run really often. Assign some shortcuts to those commands to save yourself a few extra keystrokes.
Installing Keyboard Mappings From Other Editors
If you’ve been working in another editor or IDE for some time, you may have your usual keyboard shortcuts committed to muscle memory.
You’ll find helpful keyboard mappings in extensions for Vim, IntelliJ and PyCharm, Sublime Text, Notepad++, Emacs, and Atom.
If your previous editor isn’t on this list, you may find that someone else has created a mapping extension for you. Keymaps is a helpful category on the VS Code extension marketplace.
Once you’ve installed a keymap extension, you may also find additional options to customize it beyond the defaults. For example, you can use the Vim keymap extension to configure Vim features such as whether to start in insert mode.
Customizing the User Interface
The first things you should do when jumping into the driving seat of a car are to adjust the seat, adjust the rear-view mirror, and set the steering column to the right height. Code editors are no different. They come with a default layout that works okay for everyone but not especially well for anyone. You don’t want to stretch to reach the pedals. Let’s set up your VS Code environment to suit you and make it look great on the way.
First, the Activity Bar on the left-hand side of VS Code is the main navigation tool to switch between the Explorer view used to see your files, the Source Control view, the Search view, the Run and Debug view, and the Extensions view. You’re not limited to these options. Many extensions come with views that are hidden by default. Right-click on the Activity Bar to control which views you see:
You can also use this menu to hide any views that you never use. Keep in mind that you’re not limited to the views on the list. If there are some panels within a main view—for example, you can find some additional panels nested inside the Explorer view—you can drag them to the Activity Bar to create a permanent shortcut:
Use this feature for views that you use all the time.
Using Split Screens
Python’s style guide, PEP 8, leans toward short line lengths. For wide screens, this leaves a lot of unused screen space.
Alternatively, you can use the associated keyboard shortcut:
You can also open the split editor functionality by going to View → Editor Layout or by right-clicking on a file’s tab:
This setup is really useful when writing unit tests with your test code on the left and the module you’re testing on the right.
Some file types, like Markdown, have a preview region that you can use instead. Use the Markdown: Open Preview to the Side command to open the preview editor.
Using Zen Mode for Focused Work
If you need your absolute focus on a single file or task in VS Code, then use Zen Mode by going to View → Appearance → Zen Mode to show a full-screen window with just the editor:
This feature is especially useful for blocking out noisy distractions and notifications so that you can just focus on getting your current task done.
Theming
VS Code has a huge library of themes in the VS Code Marketplace. Some of the most popular themes out there are Material Theme, Winter is Coming, Dracula, Noctis, and Monokai Pro.
Let’s focus on the Material Theme as it comes with a broad set of color schemes to suit many tastes. You can install the extension from the Extensions view. Once installed, you can select a color theme by running Preferences: Color Theme in the Command Palette.
The Material Theme looks best with a custom icon theme. Icon themes are separate extensions from the color themes, so you have to install a second extension. Search for pkief.material-icon-theme in the Extensions view to find the most popular Material icon pack for the theme. After installing this, VS Code will prompt you to switch your icon pack.
This is the Material Theme with the Palenight color theme and the Material icon pack:
You can change the icon theme at any time from the Command Palette by using the command Preferences: File Icon Theme and then selecting one of the icon themes from the list.
Installing a Better Programming Font
Programming fonts are a special group of typefaces, typically with fixed-width characters called monospace. There’s a long list of available fonts to browse at ProgrammingFonts.org:
Once you’ve selected a font, go to Nerd Fonts to download it and install the font on your operating system. The downloads at Nerd Fonts are copies of the monospace fonts with support for glyphs, otherwise known as icons, which you can use inside the terminal prompt.
After installing your selected font, you need to change the editor.fontFamily setting to the name of the new font. You can do that by navigating to Code → Preferences → Settings and then selecting Text Editor → Font in the navigation dropdown. You can change the font your editor will use by adding the name of your new font in the first field of the Font Family setting.
Setting Up Your Terminal
You’ll spend much of your Python development time inside a shell terminal. You can use a separate application, like iTerm2 or Windows Terminal, but VS Code already has a powerful built-in terminal window.
Because VS Code does need a bit of configuration to make it as powerful as a dedicated terminal application, you’ll set that up now.
Changing the Default Shell Provider
You can reconfigure the terminal window to have multiple profiles. These profiles form the dropdown list when you spawn a new terminal.
VS Code allows you to configure multiple terminal profiles. You can’t edit terminal profiles in the settings UI, so you need to use the Preferences: Open Settings (JSON) command in the Command Palette to open the settings.json file. You’ll notice that key-value pairs make up the settings file. Each key represents the configuration setting for VS Code or one of its extensions.
There are three terminal profile settings, which have the following names:
Operating System | Terminal Profile Settings |
---|---|
Windows | terminal.integrated.profiles.windows |
Linux | terminal.integrated.profiles.linux |
macOS | terminal.integrated.profiles.osx |
Once you type in the name, the editor autocompletes the default profiles into the JSON file.
Note that there’s no Python REPL profile in the default settings. You can add a profile with the key «python3-repl» to the integrated profiles JSON file so that VS Code makes it available as a profile option and drops you straight onto the REPL prompt:
Once configured, your profiles should look something like this, depending on your OS:
VS Code has two launch modes for terminals: integrated and external. Once you’ve configured the profiles, you can set the default profile for your integrated terminal by setting the value for «terminal.integrated.defaultProfile.osx» :
If something gets launched in an external terminal, it will use the default shell of your operating system. If you prefer a different terminal app, like iTerm 2 for macOS or Windows Terminal for Windows, you can change the default external terminal as well:
With this setting for macOS, for example, you’re saying that VS Code should bring up the iTerm app every time it launches an external terminal window.
There are even more settings you can change in regards to terminals in VS Code. For example, you can make VS Code activate your virtual environment automatically when you bring up a new terminal window, and you can customize the look and feel of your terminal by adding custom prompts. You’ll explore how to do both in this tutorial.
Virtual Environment Activation in the Terminal
Virtual environments are very important for managing multiple dependencies across Python projects. Visual Studio Code will activate any Python virtual environment once the interpreter is selected. If you already have a virtual environment, run Python: Select Interpreter from the Command Palette to select the Python interpreter virtual environment.
After you set the interpreter, you’ll automatically activate the virtual environment when you start a new terminal window inside VS Code:
If you already had a terminal open, you can destroy it by clicking the garbage can icon.
In the above screenshot, you can see a custom command prompt that uses the Oh My Posh prompt toolkit. In the next section, you’ll install and configure Oh My Posh. Oh My Posh is optional, especially if you already have a custom command prompt installed.
Installing Oh My Posh
Oh My Posh is one of many libraries for customizing the command prompt of your terminal. It works across Linux, macOS, and Windows. It also works with all shells like Bash, Zsh, Fish, and PowerShell. You can install Oh My Posh to spice up your terminal.
If you’re on macOS and using Bash, run the following commands to install Oh My Posh:
If you’re on macOS and using Zsh, run the following commands to install Oh My Posh:
If you’re on Windows and using PowerShell, run the following commands to install Oh My Posh:
Finally, if you’re on Linux and using Bash, run the following commands to install Oh My Posh:
When you open up a new terminal in VS Code, you’ll get this prompt:
The components on the terminal are the folder, Git branch, and Python version. Check out the list of themes for some other options.
Note: If you’re using a custom terminal prompt like Oh My Posh or Oh My Zsh, you have to select one of the installed Nerd Fonts for the glyphs to render correctly in VS Code.
Team Settings vs Personal Settings
VS Code has two levels of settings:
If a setting is declared in both, the workspace setting will override the user setting.
Global User Settings for Python
By default, the Python extension for Visual Studio Code has a very basic configuration. Many features like linting, formatting, and security checks are disabled because you need to install third-party tools like Black, Pylint, and Bandit to use them.
With these settings, you’ve managed to accomplish a couple of things that’ll be useful for your development workflow across many projects:
Workspace Settings
The following files hold the VS Code preferences:
File | Purpose |
---|---|
settings.json | VS Code settings |
launch.json | Profiles to execute your project from the Run and Debug menu |
tasks.json | Any additional tasks to execute, such as build steps |
Most of VS Code’s settings, as well as the settings for your extensions, are in these three files.
In the workspace preferences, the following predefined variables are supported:
Predefined Variable | Meaning |
---|---|
$ | Any environment variable |
$ | The path of the folder opened in VS Code |
$ | The name of the folder opened in VS Code without any slashes ( / ) |
$ | The currently opened file |
$ | The currently opened file’s workspace folder |
$ | The currently opened file relative to workspaceFolder |
$ | The task runner’s current working directory on startup |
$ | The path to the running VS Code executable |
$ | The character used by the operating system to separate components in file paths, for example, forward slash ( / ) or backslash ( \ ) |
Using these variables will keep the project settings agnostic to the environment, so you can commit them into Git.
Anyone who checks out this project will now automatically use Black as the formatter for Python files. You’ll see how this setting influences the autoformatting options in the section about setting format and lint on save.
Using the Settings Sync Extension
If you use VS Code across multiple computers, you can enable the automatic synchronization of Settings, Keyboard Shortcuts, User Snippets, Extensions, and UI State. If you haven’t used Settings Sync before, you’ll need to enable it:
Once Settings Sync is configured on all the computers you have VS Code installed on, you can see the state for each synced setting by running Settings Sync: Show Synced Data from the Command Palette, where they’ll show up under Synced Machines:
This view shows you the last synced time for each of the settings and which machines are in sync.
Linting and Formatting
All languages in Visual Studio Code can be formatted using one of the automated formatters, and the Python extension also supports linters. Linters and formatters perform different tasks:
The Python extension supports many third-party linters, and they often perform different jobs. For example, Bandit is a linter for security bugs and Flake8 is a linter for style guide compliance.
The Python extension also comes with language server tooling, which performs analysis by loading the interfaces—methods, functions, classes—from your code and the libraries you use.
At the time of writing this tutorial, the latest and greatest language server extension for Python on Visual Studio Code is Pylance.
Setting Up Pylance
Pylance is an extension that works alongside Python in Visual Studio Code to provide deeper language support and introspection of Python code. Pylance will provide auto-completions, automated module imports, better code navigation, type checking, and tons more.
To get Pylance, go to the Extensions menu on the side bar and search Pylance ( ms-python.vscode-pylance ).
Note: Pylance is now bundled with the Python extension, so you might already have it installed.
Once you have Pylance installed, there are two default configuration settings you may want to change in your user settings to get the most out of the extension.
The first setting to change is the type checking mode, which you can use to specify the level of type checking analysis performed:
You should only set python.analysis.diagnosticMode to «workspace» if you have some RAM to spare as it will consume more resources.
Pylance is most effective when it has information about the types used as the arguments to methods and functions as well as the return types.
For external libraries, Pylance will use typeshed to infer the return types and argument types. Pylance also comes with type stubs and intelligence for some of the most popular data-science libraries, like pandas, Matplotlib, scikit-learn, and NumPy. If you’re working with pandas, Pylance will give you information and examples for common functions and patterns:
For libraries that don’t have type stubs on typeshed, Pylance will do its best to guess what the types are. Otherwise, you can add your own type stubs.
Setting Format and Lint on Save
Along with the execution of the formatter, you can also have the import statements organized both alphabetically and by splitting standard library modules, external modules, and package imports into groups with the following configuration:
Unlike formatting, linting is specific to the Python extension. To enable linting, choose a linter by running Python: Select Linter on the Command Palette. You can also enable one or more linters in your settings. For example, to enable the Bandit and Pylint linters, edit your settings.json :
To run the enabled linters whenever a file is saved, add the following setting to settings.json :
You might find it helpful to have more than one linter enabled. Keep in mind that Pylance already provides many of the insights you would get from pylint, so you likely don’t need to enable both pylint and Pylance. In contrast, Flake8 provides stylistic feedback that Pylance doesn’t cover, so you can use those two together.
Testing Your Python Code in Visual Studio Code
Configuring Test Integration
To enable testing support for Python, run the Python: Configure Tests command from the Command Palette. VS Code will prompt you to select from one of the supported test frameworks and to specify which folder contains your tests.
You can edit python.testing. Args with your preferred test framework to add any additional command-line flags. The example above shows configuration options for pytest.
If you have more complex settings for pytest, put those in pytest.ini instead of the VS Code settings. That way, you’ll keep the configuration consistent with any automated testing or CI/CD tooling.
Executing Tests
Once you’ve configured the test framework and arguments for the test runner, you can execute your tests by running the Python: Run All Tests command from the Command Palette. This will start the test runner with the configured arguments and put the test output into the Python Test Log output panel:
Once test discovery has completed, each test case will have an inline option to execute or debug that case:
Failed tests will be marked as having an error. You can see the failure from the test runner in both the Python Test Log panel and by hovering over the failed test case in your code:
If you’re running tests often, you can improve your testing experience in VS Code with the testing explorer.
To enable the testing panel, right-click the side bar and make sure that Testing is checked. The testing panel shows all the tests that the Python extension discovered and provides you with many features:
You have a visual representation of the test suite grouping and which tests failed. You also have menu buttons that let you run and debug tests.
VS Code’s test system is powerful, but a lot of the functionality is disabled by default to keep it a lightweight editor. Beyond testing, there are other tasks you might want to run regularly from inside VS Code. This is where the tasks system comes in.
Using the Visual Studio Code Tasks System
Visual Studio Code supports compiled languages like Go, Rust, and C++, as well as interpreted languages like Python and Ruby. VS Code has a flexible system for executing configured tasks that the user defines, like building and compiling the code.
Python code doesn’t normally need to be compiled ahead of time because the Python interpreter does this for you. Instead, you can use the tasks system to have pre-configured tasks that you would otherwise run at the command line, such as:
VS Code tasks are commands or executables that you can run on demand using the Command Palette. There are two built-in default tasks:
Note that you can use tasks for anything that you might otherwise execute over the command line. You’re not restricted to build and test activities.
Using Tasks to Compile Wheels
If you have a setup.py file to build a package for distribution on PyPI, you can use the tasks system to automate building the source (Python) and binary (compiled Python) distribution packages.
There are a few things to note in this example, so you’ll look at the most important configurations line by line:
You’re not limited to build scripts. The task system is a great solution to Django and Flask’s management commands.
Using Tasks for Django
Are you working with a Django application, and do you want to automate running manage.py from the command line? You can create a task using the shell type. That way, you can execute manage.py with the Django sub-command you wish to run, along with any arguments:
To run this task, use the Tasks: Run Task command in the Command Palette and choose the Make Migrations task from the list.
Chaining Tasks
Expanding on the setup.py example, if you want to first build a source distribution of your package, you can add the following task to tasks.json :
Within the default build task, you can then add a property dependsOn along with a list of the task labels that need to run first:
The next time you run this task, it will run all dependent tasks first.
If you have multiple tasks that this task depends on and they can be run in parallel, add «dependsOrder»: «parallel» to the task configuration.
Using Tasks to Run Tox
Now you’ll explore tox, which is a tool that aims to automate and standardize testing in Python. The Python extension for Visual Studio Code doesn’t come with tox integration. Instead, you can use the tasks system to set tox as the default test task.
Tip: If you want to get started quickly with tox, then install tox with pip and run the tox-quickstart command:
This will prompt you through the steps of creating a tox configuration file.
To automate running tox with your tox configuration, add the following task to tasks.json :
You can run this task using Tasks: Run Test Task from the Command Palette, and the task will execute tox with the output within the Terminal tab:
If you have a few tasks and need to run them often, it’s time to explore a great extension that adds some shortcuts in the UI for running configured tasks.
Using the Task Explorer Extension
Click the arrow next to any task to execute it, and click the refresh icon at the top if you change your task’s configuration.
Debugging Your Python Scripts in Visual Studio Code
The Python extension for Visual Studio Code comes bundled with a powerful debugger that supports local and remote debugging.
The simplest way to run and debug a simple Python script is going to the Run → Start Debugging menu and choosing Python File from the selection. This will execute the current file using the configured Python interpreter.
You can set breakpoints anywhere in the code by clicking in the gutter to the left of the line number. When breakpoints are hit as the code executes, the code will pause and wait for instruction:
The debugger adds a menu of controls: Continue, Step Over, Step Into, Step Out, Restart, and Stop Execution:
On the left panel, you can perform common debugging actions, such as exploring local and global variables and Python’s call stack. You can also set watches, which you’ll learn more about in the next section.
Setting Watches
Watches are expressions that persist between debugging sessions. When you stop execution and start debugging again, you’ll keep any watches from your last session.
You can add a variable to the Watch panel from the Variables panel by right-clicking a variable and selecting Add to Watch.
You can also add any Python expression to the Watch list by clicking the + icon. Expressions can contain:
You’ll get the current result of each expression in real time whenever a breakpoint is hit. VS Code will also update the value of each watch while you step through your debugging session:
You can expand complex types like dictionaries and objects using the arrow on the left.
So far, you’ve seen the debugger for a single Python file, but many Python applications are modules or require special commands to start.
Configuring a Launch File
Note: To see the expected result of the upcoming configuration, you need to have a working FastAPI project set up and the async web server uvicorn installed in the Python environment you’re using.
For an example of working with launch profiles in VS Code, you’ll explore how to use the ASGI server uvicorn to start a FastAPI application. Normally, you might just use the command line:
Instead, you could set up an equivalent launch configuration in launch.json :
Once you’ve added this configuration, you should find your new launch configuration ready to start under the Run and Debug panel:
Whatever you configured as the first launch configuration will run when you press F5 or select Run → Start Debugging from the top menu.
Mastering Remote Development
VS Code supports three remote development profiles:
All three options are provided by the Remote Development extension pack ( ms-vscode-remote.vscode-remote-extensionpack ). You need to install this extension pack for the remote debugging features to display in VS Code.
Remote Development With Containers
You need to install the Docker runtime on your machine to use remote debugging for containers. If you don’t already have Docker installed, you can download it from the Docker website.
Once Docker is running, go to the Remote Explorer tab on the left navigation menu. Change the Remote Explorer dropdown to Containers, and you’ll see a view with panels:
These panels aren’t populated if you have a fresh Docker install.
If you already have Docker images installed and running, the three panels might be populated:
For example, if you installed the Try Out Development Container: Python by following the steps outlined in VS Code’s containers tutorial, your VS Code Remote Explorer tab will show the name of the running container across the panels mentioned earlier:
Use these panels as a quick way of managing any Docker containers that your project depends on.
In general, there are three primary ways of running the Remote Containers extension:
If you’re planning on working within containers and VS Code a lot, spending the extra time to create a development container will pay off.
Note: You can learn how to create a development container in more detail by reading through the official VS Code documentation.
A quick way to get started using a dev container is by creating it from your current workspace:
Dev containers have two required files:
You can also add options for port forwarding if you’re developing an application that provides network services, like a web app. For the full list of options, you can go through the devcontainer.json reference.
After making changes to either the Dockerfile or the devcontainer specification, rebuild the container from the Remote Explorer by right-clicking the running container and selecting Rebuild Container:
Beyond the functionality of the Remote Development extension pack’s extension for remote debugging, there’s a Docker extension for VS Code. You’ll cover this extension at the end of the tutorial and find even more features.
Remote Development With SSH
By running Remote-SSH: Open SSH Configuration File in the Command Palette, you can open up the local SSH configuration file. This is a standard SSH config file for you to list hosts, ports, and paths to private keys. The IdentityFile option defaults to
Here’s an example configuration of two hosts:
Once you save the configuration file, the Remote Explorer tab will list those SSH hosts under the SSH Targets dropdown option:
To connect to that server, click on Connect to Host in New Window, which is the icon to the right of any host. This will open a new VS Code window with the remote host.
Once connected, click Open Folder under the Explorer view. VS Code will show you a special folder navigation menu that displays the available folders on the remote host. Navigate to the folder where your code is located, and you can start a new workspace under that directory:
In this remote workspace, you can edit and save any files live on the remote server. The Terminal tab is automatically set as the SSH terminal for the remote host if you need to run any additional commands.
Remote Development With WSL
Windows Subsystem for Linux, or WSL, is a component for Microsoft Windows that enables users to run any number of Linux distros on their Windows OS without the need for a separate hypervisor.
VS Code supports WSL as a remote target, so you can run VS Code for Windows and develop for Linux under WSL.
Using WSL with VS Code first requires that WSL is installed. Once WSL is installed, you need to have at least one distro available.
The easiest way to install WSL on the latest version of Windows 10 is to open a command prompt and run:
If you already have code in WSL, run Remote-WSL: Open Folder in WSL from the Command Palette in VS Code. Select the target directory for your code in the Linux subsystem.
If your code was checked out in Windows, run Remote-WSL: Reopen Folder in WSL from the Command Palette.
The Remote Explorer will remember your configured WSL targets and let you reopen them quickly from the WSL Targets dropdown in the Remote Explorer view:
If you want a reproducible environment, consider creating a Dockerfile instead of working directly on the WSL host.
Working With Data Science Tools
VS Code is great for working on Python for application development and web development. It also has a powerful set of extensions and tools for working with data science projects.
So far, you’ve mostly covered the Python extension for VS Code. There’s also the Jupyter Notebooks extension, which integrates the IPython kernel and a notebook editor into VS Code.
Installing the Jupyter Notebook Extension
To get started with Jupyter Notebooks on VS Code, you’ll need the Jupyter Extension ( ms-toolsai.jupyter ).
Note: Jupyter Notebooks support is now bundled with the Python extension, so don’t be surprised if you already have it installed.
Jupyter Notebooks supports pip as the package manager, as well as conda from the Anaconda distribution.
Data science libraries for Python often require compiled modules written in C and C++. You should use conda as the package manager if you’re using a lot of third-party packages because the Anaconda distribution has resolved the build dependencies on your behalf, making it easier to install packages.
Getting Started With Jupyter Notebooks in VS Code
Note: The rest of this section uses the conda package manager. You’ll need to have Anaconda installed if you want to use the commands shown in this section.
In VS Code, you can use any existing conda environment. Instead of installing packages into the base environment, you can create a conda environment specifically for VS Code from your terminal:
Once you’ve installed the dependencies, run the Python: Select Interpreter command from the VS Code Command Palette and search for vscode to select the new conda environment:
Note: If the conda environment is not available in the list, you may need to reload the window by running the Developer: Reload Window command from the Command Palette.
Once selected, open a notebook in VS Code and click the Select Kernel button on the right or run the Notebook: Select Notebook Kernel command from the Command Palette. Type vscode to select the newly created conda environment with the dependencies installed:
Selecting your new conda environment as the kernel for your notebook will give your notebook access to all the dependencies that you installed in that environment. It’s necessary for executing the code cells.
Once the kernel is selected, you can run any or all of the cells and see the output of the operations displayed right inside VS Code:
Once the notebook has executed, the Jupyter Extension will make any of the intermediate variables such as lists, NumPy arrays, and pandas DataFrames available in the Jupyter: Variables view:
You can bring this view into focus by clicking the Variables button at the top of the notebook or by running the Jupyter: Focus on Variables View command.
For the more complex variables, choose the icon to open the data in the data viewer.
Using the Data Viewer
To access the data viewer, you can expand complex variables inside the variables view by clicking on Show variable in data viewer. This option is represented by an icon shown on the left of a row that represents a complex variable:
The data viewer supports inline filtering and paging for large data sets. If you’re plotting large data sets in Matplotlib, the Jupyter Extension supports Matplotlib widgets instead of SVG rendering.
Using the Rainbow CSV Extension
If you work with CSV or TSV input data, there’s a useful extension called Rainbow CSV ( mechatroner.rainbow-csv ) that enables you to open and visualize CSV files in VS Code:
Each column is colorized, giving you a quick way to spot missing commas. You can also align all columns by running the Rainbow CSV: Align CSV Columns command from the Command Palette.
Note: If you’re looking for an example CSV file to try this extension, you can pick a CSV file for download from the official statistics page of the New Zealand government.
The Rainbow CSV extension also comes with a Rainbow Query Language (RBQL) query tool that lets you write RBQL queries on the CSV data to create filtered data sets:
You can access the RBQL console by running Rainbow CSV: RBQL in the Command Palette. After executing a query, you’ll see the results in a new tab as a temporary CSV file that you can save and use for further data analysis work.
Throughout this tutorial, you’ve installed a couple of useful extensions for VS Code. There are a lot of useful extensions available. In the final section of this tutorial, you’ll learn about some extra extensions you haven’t covered so far that you might also want to try out.
Adding Bonus Extensions to Visual Studio Code
The VS Code Marketplace has thousands of extensions. The selection of extensions covers anything from language support, themes, spell checkers, and even mini-games.
In this tutorial so far, you’ve covered a number of extensions that make Python development in Visual Studio Code more powerful. These last four extensions are optional—but could make your life easier.
Code Spell Checker
Code Spell Checker ( streetsidesoftware.code-spell-checker ) is a spell checker that inspects variable names, text inside strings, and Python docstrings:
The Code Spell Checker extension will highlight any suspected misspellings. You can either correct the spelling from the dictionary or add the word to a user or workspace dictionary.
The workspace dictionary will live inside the workspace folder, so you can check it into Git. The user dictionary is persisted across all your projects. If there are lots of keywords and phrases you use often, you can add them to the user dictionary.
Docker
The Docker extension ( ms-azuretools.vscode-docker ) makes it easy to create, manage, and debug containerized applications:
Thunder Client
Thunder Client ( rangav.vscode-thunder-client ) is an HTTP client and UI for VS Code designed to aid testing of REST APIs. If you’re developing and testing APIs in frameworks like Flask, FastAPI, or Django Rest Framework, you may already use a tool like Postman or curl to test your application.
Inside Thunder Client, you can create HTTP requests and send them to your API, manipulate headers, and set payloads of text, XML, and JSON:
Thunder Client is a great alternative to Postman or curl, and since you can use it right inside of VS Code, you can avoid switching between applications when testing and developing your REST APIs.
VS Code Pets
VS Code Pets ( tonybaloney.vscode-pets ) is a fun extension that puts one or many small pets in your VS Code window:
You can customize the pets, customize their environments, and play games with them.
Note: As the author of this tutorial, I’ll say that this is a great extension—but I may be biased because I created it.
This is just a snapshot of the extensions on the marketplace. There are thousands more to discover for additional language support, UI improvements, or even Spotify Integration.
Conclusion
Visual Studio Code’s Python tooling is evolving rapidly, and the team is putting out updates with bug fixes and new features monthly. Make sure you install any new updates to keep your environment on the latest and greatest.
In this tutorial, you’ve seen an overview of some of the more advanced features in Visual Studio Code, the Python and Jupyter extensions, as well as some bonus extensions.
You learned how to:
You can use this knowledge to put yourself on track to be a VS Code power user.
Play around with some of these extensions and test them out as you work on your next project. You’ll find that some VS Code features will be more useful for you than others. Once you get a feel for some of the customizations and extensions, you’ll likely find yourself in the VS Code docs looking for more or even coding your own extensions!
Language Configuration Guide
The contributes.languages Contribution Point allows you to define a language configuration that controls the following Declarative Language Features:
Here is a Language Configuration sample that configures the editing experience for JavaScript files. This guide explains the content of language-configuration.json :
Comment toggling
VS Code offers two commands for comment toggling. Toggle Line Comment and Toggle Block Comment. You can specify comments.blockComment and comments.lineComment to control how VS Code should comment out lines / blocks.
Brackets definition
When you move the cursor to a bracket defined here, VS Code will highlight that bracket together with its matching pair.
Moreover, when you run Go to Bracket or Select to Bracket, VS Code will use the definition above to find the nearest bracket and its matching pair.
Autoclosing
The notIn key disables this feature in certain code ranges. For example, when you are writing the following code:
The single quote will not be autoclosed.
Pairs that do not require a notIn property can also use a simpler syntax:
Users can tweak the autoclosing behavior with the editor.autoClosingQuotes and editor.autoClosingBrackets settings.
Autoclosing before
By default, VS Code only autocloses pairs if there is whitespace right after the cursor. So when you type < in the following JSX code, you would not get autoclose:
However, this definition overrides that behavior:
Autosurrounding
When you select a range in VS Code and enter an opening bracket, VS Code surrounds the selected content with a pair of brackets. This feature is called Autosurrounding, and here you can define the autosurrounding pairs for a specific language:
Users can tweak the autosurrounding behavior with the editor.autoSurround setting.
Folding
In VS Code, folding is defined either indentation-based, or defined by contributed folding range providers:
Word Pattern
Indentation Rules
indentationRules defines how the editor should adjust the indentation of current line or next line when you type, paste, and move lines.
Notice that editor.formatOnPaste setting is controlled by the DocumentRangeFormattingEditProvider and not affected by auto indentation.
On Enter Rules
onEnterRules defines a list of rules that will be evaluated when Enter is pressed in the editor.
If all the specified properties match, the rule is considered to match and no further onEnterRules will be evaluated. An onEnterRule can specify the following actions:
How to change visual studio code settings
I am trying to changes visual studio code settings.json but it is not working. I have updated this in C:\Users\Userid\AppData\Roaming\Code\User\settings.json but not working. How to edit settings.json file in vs code?
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
VSCode’s settings are split into 2 categories: User and Workspace.
User settings
Settings that apply globally to any instance of VS Code you open.
VSCode settings pane with User Settings tab open
Editing JSON schemas
The VSCode settings page does not allow direct editing of JSON Schemas. To edit JSON schema settings: 1. Search JSON schemas in the VSCode settings page 2. Click «edit in settings.json» 3. Edit settings 4. Done!
JSON schema setting in VSCode
Workspace settings
Settings stored inside your workspace and only apply when the workspace is opened.
Workspace settings override user settings.
To edit workspace settings, follow steps for user settings, except click the Workspace Settings tab instead. Note that workspace settings will override user settings
Why does Typescript ignore my tsconfig.json inside Visual Studio Code?
I got my project setup like this
and here’s my tsconfig.json
What I’m wondering is, why does VSC indicate errors such as
when clearly there is no error at all ( «experimentalDecorators»: true is set in tsconfig.json ), and the app transpiles just fine? And it’s not just decorators, Promise and the like is highlighted as well (I made sure to have tsconfig.json in the same folder as typings and I got the typings for es6-shim installed).
Not sure if it matters, but I’m on typescript@2.0.0-dev.20160707 at the moment.
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Short Answer
VS Code ignores your tsconfig.json when you use a newer version of TypeScript than the one that VS Code provides out of the box.
How to use a newer TypeScript version in VS Code
The Visual Studio Code Tutorial Worth Learning
Read more tutorials by Adam Bertram!
Table of Contents
Every cowboy needs a horse, every Batman needs a Robin, and every coder needs a great code editor. When you work with code every day, you must have a go-to code editor. For many developers out there, Visual Studio (VS) Code is their editor of choice. Stick around for this Visual Studio Code tutorial.
In this post, you’re going to learn all about VS Code and each of its powerful features. If you’re looking for an in-depth review of VS Code, including thorough explanations of everything it’s capable of, keep reading.
This blog post is a snippet of a chapter from the eBook From Admin to DevOps: The BS Way to DevOps in Azure. If you like this chapter and want to learn about doing the DevOps in Azure, check it out!
Table of Contents
The Interface
This Visual Studio Code tutorial will be using VS Code 1.53.2. If the instruction and screenshots look a little different, chances are you’re using a new version. All effort has been made to focus on the less version-specific aspects of VS Code, though.
When you open up VS Code for the first time, you will see a user interface that looks like the following screenshot. You’ll see that VS Code has a few main areas you’ll be staring at day in and day out.
The main VS Code interface
The main VS Code interface can be broken down into five distinct areas:
Commands and the Command Palette
There’s a lot to do in VS Code, especially if you have installed many extensions (covered later). You can control a lot of that functionality via the typical File, Edit, and View menus at the top of the window but not everything.
The easiest way to make things happen in VS Code is via commands found in the command palette. The command palette is a menu that appears at the top of the screen when you click on the View menu and select Command Palette, or you hit Ctrl-Shift-P on your keyboard.
In the following screenshot, you can see an example of the command palette.
VS Code command palette
The command palette is where you will find all functionality of VS Code. The command palette is great because all functionality for managing tasks, settings, snippets, and more are located in a single menu (covered later).
The command palette is where you will find everything you can do in both a default VS Code installation and configure any extension you have installed.
Settings
You can customize just about every aspect of VS Code using settings. Settings control both default VS Code functionality and installed extensions. Settings are stored as JSON files, and VS Code defines many of them out of the box.
To manage settings, open the Command Palette with Ctrl-Shift-P. Type “settings” and choose Preferences: Open Settings (JSON) as shown below. Be warned though, there are a lot of settings!
Settings in the command palette
VS Code will then open up a JSON file displaying all of its currently-defined settings.
There’s an easier way to manage settings, though, via the VS Code UI. VS Code provides a UI to browse settings, as you can see in the following screenshot. You can find this UI by opening the command palette again and choosing Preferences: Open Settings (UI).
The UI for VS Code settings allows you to search for settings and break them down by categories along the screen’s left side.
Managing VS Code settings
There’s absolutely no way this Visual Studio Code tutorial will come close to explaining all of the settings available. Take a minute to browse around and see what tweaks you can make to VS Code.
Extensions
One of the most important features of VS Code is its extensions. Out of the box, VS Code supports common code editor features like syntax highlighting, Intellisense, etc. It understands the type of code you’re writing and adapts to that in many different ways. But it doesn’t understand all languages.
For example, perhaps you’re working on an ARM template. An ARM template is JSON. Lucky for you, VS Code understands JSON out of the box. If you open up a file with a JSON extension, VS Code assumes it’s a JSON file and applies all its features accordingly. In the following screenshot, you can see a couple of these features.
JSON is just plain text, after all. For VS Code to know when a section should be collapsible and what text to change colors, it must understand JSON’s structure. VS Code applies these features differently depending on the type of file opened.
VS Code extensions defined in JSON
Even though an ARM template is created in JSON and VS Code understands JSON doesn’t mean VS Code understands ARM templates.
Even though VS Code doesn’t natively understand ARM templates doesn’t mean it can’t. Developers can add functionality to VS Code. In this case, developers can add functionality around ARM templates via an extension.
An extension is a small package you can load into VS Code that makes working with various resources easier.
You can manage extensions via the extension icon in the Activity Bar, as shown below. Once you click on the icon on the left, you should immediately see a list of the most popular extensions in the Extension Marketplace.
The Extension Marketplace is where developers store extensions that you can download and install at will.
You can see in the following screenshot extensions aren’t just language-specific either. Extensions extend VS Code functionality across a wide range of features. If you’re developing code around a specific product, always search the Extension Marketplace to see if any extension is available.
VS Code extensions
For the ARM template example, search for “arm,” as shown below, and see what comes up. Notice that there are many different extensions for ARM templates, some by Microsoft and third-party developers. Clicking on the green Install button beside each extension will immediately download and install the extension.
Filtering extensions
Extensions are what make VS Code truly shine. Extensions allow you to do so much with VS Code and remove the need to leave the application to do other related tasks.
Snippets
Have you ever typed the same code snippet over and over again? As with software development, you should always strive to work via the Don’t Repeat Yourself (DRY) principle.
Sure, you could accomplish the same thing by typing up that function declaration snippet for the 50th time, but what’s the point? And who’s to say you’re actually going to write it the same way every time anyway? If you need an automated way to create text blurbs, you need to use snippets.
VS Code snippets are a handy feature everyone should be using no matter what kind of development you’re doing. Snippets allow you to type a few characters in a code editor tab that quickly expands to whatever you need.
Snippets exist by language or extension and are stored in JSON files. For example, you can have a set of PowerShell, ARM template, Python, C#, and Javascript snippets installed simultaneously.
You can find snippets by opening up the command palette with Ctrl-Shift-P, typing “snippets” and hitting Enter.
Configure User Snippets command palette entry
The snippets menu will appear where you can edit all of the default language snippets. If you’ve installed extensions that come with a set of snippets, they will show up here as well.
Viewing language-specific snippets
If you navigate to a particular snippet with the arrow keys and hit Enter or click on one, VS Code will bring up the JSON snippets files in an editor tab. In the following screenshot, you can see that many will have a single JSON element commented out with instructions on creating a snippet of your own.
Viewing a language snippet file
Each snippet is a single JSON element that matches a particular syntax. You can learn more about snippet syntax on Microsoft’s VS Code snippets page.
Once you create the snippet, you can then call the snippet in the editor. In the following screenshot, you can now see if you type “func” in a PowerShell script, VS Code provides you with a list of options available to you.
VS Code extensions can add “Intellisense” features
Once you select func in the editor window and hit Enter, func will turn into the code snippet on the left in the image below. You can see that VS Code highlights functionName and has a cursor on line eight. These tab stops allow you to edit these parts of the expanded snippet.
Defining your own snippets
Snippets are huge time-savers if you spend the time to build out all of the common routines you find yourself doing day in and day out. The snippets shown in this Visual Studio Code tutorial were just a taste of what you can do.
The Integrated Terminal
When you’re developing scripts or software, you don’t just write a bunch of code at once, and it works perfectly. If only that were true. Instead, you write a little code, test it out to see if it works, tweak and repeat until you’ve accomplished your task.
To run code in development, you’d typically have to Alt-Tab to another window like a console or other external tool. If that external tool is available via the command-line or you’re writing PowerShell code, you don’t have to leave VS Code and use the integrated terminal instead.
The integrated terminal is integrated directly into VS Code. It isn’t an external console or window. It sits below your editor tabs at all times (unless you close it). By default, the terminal is a legacy command prompt (cmd.exe) on Windows or Bash on Linux and macOS. However, as you can see below, once you install the PowerShell extension, VS Code defaults to a PowerShell console.
The PowerShell integrated terminal
You can use the integrated terminal just like you would a typical console by typing commands, getting output, etc. But the integrated terminal provides a few additional benefits. For starters, one of the most useful benefits is the ability to run pieces of code while in development.
For example, let’s say you’re working on a PowerShell script and you’d like to test a single line. Instead of copying out the code and pasting it into another PowerShell window, click on any position on that line and hit the F8 key. VS Code then reads the entire line and executes it in the integrated terminal (if you have the PowerShell extension installed).
Running code in the integrated terminal
In this Visual Studio Code tutorial, you’re only going to learn the integrated terminal basics. To learn more about the integrated terminal, be sure to check out Microsoft’s documentation.
Working as a Team with Workspaces
This tutorial has, so far, assumed you have been using VS Code independently. It’s assumed that it’s just you typing away at your keyboard. But that doesn’t reflect the real world. In the real world, chances are you’ll be working on a team.
While you were digging through the settings, installing extensions, and creating some snippets, you were changing VS Code’s configuration for you. What if you’re on a team that could also use the tweaks you made to your VS Code installation? In that case, you need to share those settings. One way to do that is with a workspace.
In VS Code, a workspace is a collection of folders and settings that control behavior, typically for a single project.
Think of an app your team is developing that contains many folders, a Git repo, and perhaps a certain coding standard everyone on the teams needs to abide by. A single “project” is a good use case for a workspace.
To create a workspace, open one or more folders, go up to the File menu, click on Save Workspace As, and save the file. VS Code saves the workspace to a file with a code-workspace file extension. This file contains everything saved to the workspace.
Workspace and Settings
Workspaces come into play, especially when it comes to settings. When you define settings in VS Code, you do so at either the user-level or workspace-level. When working on a team project where everyone uses VS Code, you’ll probably want to create a shared workspace. To do that, open up the folders involved and save the workspace.
Once you’re working within a workspace, open the command palette, type “settings,” and you’ll now see another option for Workspace Settings, as shown in the following screenshot.
Opening workspace settings
Selecting the Open Workspace Settings option will then bring you back to a familiar Settings screen. This time though, you’ll have two groups of settings; User and Workspace. Selecting Workspace and making a change here will save that setting change to the workspace file instead of your own VS Code installation.
User vs. workspace settings
Workspaces are a great way to group snippets, settings, and other items to share across a team to ensure a consistent experience.
Conclusion
This Visual Studio Code tutorial was meant to give beginners a jumpstart with this IDE. Even though it’s impossible to cover the VS Code’s extent in 3,000 words, this tutorial has covered the main features.
If you’d like to learn more about Visual Studio Code and dig into any of the features covered here, be sure to check out the Microsoft documentation.
Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.
More from ATA Learning & Partners
Recommended Resources!
Recommended Resources for Training, Information Security, Automation, and more!
Get Paid to Write!
ATA Learning is always seeking instructors of all experience levels. Regardless if you’re a junior admin or system architect, you have something to share. Why not write on a platform with an existing audience and share your knowledge with the world?
ATA Learning Guidebooks
ATA Learning is known for its high-quality written tutorials in the form of blog posts. Support ATA Learning with ATA Guidebook PDF eBooks available offline and with no ads!
What are ALL configuration files used by Visual Studio Code?
I’m wondering if there’s also another place.
For example, if you create a file without using New File button, e.g. from terminal:
And then you open it in the editor, you will be prompted with a dialog like this:
If you hit Don’t Show Again. and repeat the same experiment in the same directory or in another, VS Code will remember it (it will not present the dialog a second time).
I know it’s not an important thing. But I want to know where this is stored.
So, are there any other config file that VS Code uses?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You can access your defaultSettings.json by typing «default settings» in the command palette ( Shift + Cmd + P or Shift + Ctrl + P in Windows/Linux).
You can access your user settings.json file by pressing Cmd+, (or Ctrl+, in Windows/Linux).
The single-folder settings go into the /.vscode/settings.json file. The single-folder state is a legacy feature. You can insert both repository-wide and workspace-wide settings inside the /.vscode/settings.json file when in a single-folder state but workspace settings stop working if you turn that into a workspace. This can be confusing because VS Code creates an implicit/unsaved workspace if you choose the » Remove folder from Workspace » or the » Add folder to workspace » options in your file explorer.
The repository settings go into the /.vscode/settings.json file.
I’ve recorded a video on where settings are applied that contains a slight misconception, which I’m hoping to correct soon, around the single-folder legacy functionality that I was not aware of at the time of the recording. I hope this helps 🙂
Depending on your platform, the user settings file is located here:
If you take a look at the Code folder, there are a bunch of other files stored there:
Those contain all the settings/configurations that VS Code maintains (apart from the .vscode folder in your workspace). If you delete the Code folder, your VS Code would then behave like it was freshly installed.
Most of them aren’t easily readable like JSON though, and most are stored in SQL DB files (.vscdb). For example, for remembering that «Don’t Show Again» prompt for files with .abc extensions, it’s stored in User/globalStorage/state.vscdb. Use a SQLite browser (like this) to open up that file, and you’ll see this:
. which stores the setting to not prompt me again for .csv and .abc files. (Try removing the «abc» from the DB value, and VS Code will prompt you again.)
For workspace-specific settings, they are stored in User/workspaceStorage, where each workspace is organized into folders like this:
Go into any one, and check the workspace.json to know which workspace the DB file is for. Then again open the state.vscdb to see something like this:
. which shows settings for remembering which files are opened, etc..
Источники:
- http://ourtechroom.com/tech/open-settings.json-file-vscode/
- http://github.com/microsoft/vscode-docs/blob/main/docs/languages/json.md
- http://vscode-docs.readthedocs.io/en/latest/customization/userandworkspace/
- http://aregsar.com/blog/2020/my-visual-studio-code-setup/
- http://github.com/Geri-Borbas/VSCode.Documentation/blob/master/docs/getstarted/settings.md
- http://code.visualstudio.com/docs/cpp/customize-default-settings-cpp
- http://code.visualstudio.com/docs/languages/json
- http://stackoverflow.com/questions/34977789/cannot-change-visual-studio-code-settings
- http://stackoverflow.com/questions/63211082/cannot-edit-default-vscode-json-settings
- http://stackoverflow.com/questions/58900482/what-are-all-configuration-files-used-by-visual-studio-code
- http://stackoverflow.com/questions/55371839/how-to-change-visual-studio-code-settings
- http://stackoverflow.com/questions/55434687/vscode-settings-json-is-missing
- http://stackoverflow.com/questions/59466769/how-do-i-update-my-config-file-in-vs-code
- http://stackoverflow.com/questions/53369371/what-is-the-location-of-the-default-settings-file-of-vscode
- http://abcinblog.blogspot.com/search/label/VSCode
- http://stackoverflow.com/questions/63211082/cannot-edit-default-vscode-json-settings?rq=1
- http://code.visualstudio.com/docs/languages/jsconfig
- http://github.com/alefragnani/vscode-settings
- http://docs.microsoft.com/ru-ru/visualstudio/ide/customize-build-and-debug-tasks-in-visual-studio?view=vs-2022
- http://stackoverflow.com/questions/35368889/how-can-i-export-settings
- http://techrocks.ru/2020/08/06/vs-code-extensions-vs-settings/
- http://stackoverflow.com/questions/60077869/vscode-settings-json-is-empty
- http://docs.microsoft.com/ru-RU/visualstudio/ide/customize-build-and-debug-tasks-in-visual-studio?view=vs-2019
- http://stackoverflow.com/questions/30056721/how-do-i-configure-vs-code-to-enable-code-completion-on-json-files-jsonschema
- http://stackoverflow.com/questions/33392127/is-there-any-way-to-sync-my-visual-studio-code-settings-between-instances
- http://stackoverflow.com/questions/36108515/how-to-reset-settings-in-visual-studio-code
- http://stackoverflow.com/questions/55371839/how-to-change-visual-studio-code-settings?lq=1
- http://stackoverflow.com/questions/46284462/how-to-exclude-settings-json-from-vs-code-search
- http://www.hongkiat.com/blog/customizing-visual-studio-code/
- http://code.visualstudio.com/docs/editor/variables-reference
- http://stackoverflow.com/questions/55371839/how-to-change-visual-studio-code-settings/55371862
- http://www.kindacode.com/article/vs-code-how-to-use-custom-settings-for-a-project/
- http://code.visualstudio.com/api/references/contribution-points
- http://github.com/microsoft/vscode-docs/blob/main/docs/getstarted/tips-and-tricks.md
- http://docs.microsoft.com/en-us/visualstudio/ide/customize-build-and-debug-tasks-in-visual-studio?view=vs-2019
- http://stackoverflow.com/questions/63211082/cannot-edit-default-vscode-json-settings/70614844
- http://reddeveloper.ru/questions/gde-nakhodit-sya-fail-nastroyek-po-umolchaniyu-vscode-0l5Ae
- http://stackoverflow.com/questions/32964920/should-i-commit-the-vscode-folder-to-source-control
- http://stackoverflow.com/questions/70840230/i-cant-find-python-json-settings-in-vs-code
- http://superuser.com/questions/1080682/how-do-i-back-up-my-vs-code-settings-and-list-of-installed-extensions
- http://github.com/microsoft/vscode-docs/blob/main/docs/getstarted/userinterface.md
- http://ilyachalov.livejournal.com/258404.html
- http://realpython.com/advanced-visual-studio-code-python/
- http://code.visualstudio.com/api/language-extensions/language-configuration-guide
- http://stackoverflow.com/questions/55371839/how-to-change-visual-studio-code-settings/55373799
- http://stackoverflow.com/questions/38268776/why-does-typescript-ignore-my-tsconfig-json-inside-visual-studio-code
- http://adamtheautomator.com/visual-studio-code-tutorial/
- http://stackoverflow.com/questions/58900482/what-are-all-configuration-files-used-by-visual-studio-code/58943928