© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
S. bin UzayrOptimizing Visual Studio Code for Python Developmenthttps://doi.org/10.1007/978-1-4842-7344-9_1

1. Introduction to Visual Studio Code

Sufyan bin Uzayr1  
(1)
Barabanki, India
 

Visual Studio Code (VS Code) is an open-source code editor created by Microsoft for Windows, Linux, and macOS (Figure 1-1). Widely popular standard features include support for debugging, syntax highlighting, automatic code completion, snippets, code restructuring, and embedded Git. Users are free to change the design theme, keyboard shortcuts, and preferences, as well as install additional extensions to upgrade the overall project functionality.

Microsoft first introduced VS Code at the 2015 Build conference. By 2019 VS Code ranked as the most popular developer environment tool, with 50.7% of 87,317 respondents reporting that they regularly apply it.
../images/514155_1_En_1_Chapter/514155_1_En_1_Fig1_HTML.jpg
Figure 1-1

Visual Studio Code, a free and open-source code editor

In this chapter, we will walk you through setting up VS Code as well as provide an overview of the basic features:
  • User interface: viewing the documentation for VS Code.

  • Setup overview: documentation for starting up and running with VS Code, including platform-related setup.

  • Keyboard shortcuts: customization options for your own shortcuts and installation of Keymap extensions.

  • Keybinding extensions: how to install a Keymap extension to bring the keybindings from your previous editor to VS Code.

User Interface

According to the original intent, VS Code is a code editor. Similar to many other code editors, VS Code has a common user interface and layout of an explorer on the left, displaying all of the files and folders you have access to, and an editor on the right, presenting the content of the files you have opened.

Basic Layout

VS Code comes with a straightforward yet intuitive layout that utilizes all the space provided for the editor, while leaving some room to browse and access the full context of your folder or the ongoing project. The User Interface is divided into five main areas:
  • Editor: The main space for you to edit current files. You can open as many editors as you need side by side, as well as vertically and horizontally.

  • SideBar: This area has different views such as the Explorer, to provide a maximum assistance while you are working on your project.

  • Status Bar: Information about the current project and the files you are editing.

  • Activity Bar: Placed on the far left-hand side, this area enables you to switch between views and gives you additional context-specific measures—for instance, the number of outgoing changes.

  • Panels: You can show different panels below the editor area for output or debug content, errors, and warnings, or integrated information. The panel can also be shifted to the right for more vertical space.

Each time you launch VS Code, it opens up in the same state it was in when you last left it. The folder, layout, and opened files will be preserved the same. Open files in each editor are displayed with tabbed headers (Tabs) at the top of the editor region. To learn more information about tabbed headers, see the details of the Tabs section. You can also move the Sidebar to the right-hand side (View ➤ Move Side Bar Right) or enhance its visibility (Ctrl+B).

Side-By-Side Editing

As previously mentioned, you can open as many editors as you like side-by-side vertically as well as horizontally. If you already have one editor open, there are various ways of placing another editor to the side of the existing one:
  • Alt-click on a file in the Explorer.

  • Ctrl+ to split the active editor into two.

  • Open to the Side (Ctrl+Enter) from the Explorer context menu on a file.

  • Click the Split Editor button in the upper right of an editor.

  • Drag and drop a file to any side of the editor region.

  • Ctrl+Enter (macOS: Cmd+Enter) in the Quick Open (Ctrl+P) file list.

Once you open another file, the editor that is in progress will display the content of that file. So if you have two editors side by side and you need to open file doc.cs into the right-hand editor, make sure that editor is active (by clicking on it) before opening file doc.cs.

By default, editors are made to open on the right-hand side of the active one. You can change this pattern through the setting workbench.editor.openSideBySideDirection and modify to open new editors to the bottom of the active one instead. At the same time, when you have more than one editor active, you can switch between them easily by holding the Ctrl (macOS: Cmd) key and pressing 1, 2, and 3. In addition, you can resize editors and reorder them if you would like to: simply drag and drop the editor title area to reposition or resize the editor.

Minimap

A Minimap (code outline) allows you to get a high-level overview of your source code, which is quite useful for easy navigation and code comprehension. A file’s minimap is displayed on the right side of the editor. You can also click or drag the shaded area to quickly switch to different sections of your file. It is also worth noting that you can move the minimap to the left-hand side or even disable it completely by simply setting “editor.minimap.side”:, “left”, or “editor.minimap.enabled”: false in your user or workspace settings.

Indent Guides

The image above the editor also shows vertical lines or indentation guides that are there to help you freely observe matching indent levels. If you would like to turn off those indent guides, you should set “editor.renderIndentGuides”: false in your user or workspace settings.

Breadcrumbs

If you take a look at the editor once again, you will notice it has a navigation bar above its contents that is named Breadcrumbs. It is there to show your current location and let you quickly navigate between folders, files, and symbols.

Breadcrumbs also tend to display the file path, and if the active file type has language support for symbols, it displays the symbol path up to the cursor position. You can switch off Breadcrumbs with the View ➤ Show Breadcrumbs simple command. You can also access the same information about the Breadcrumbs feature at the Breadcrumbs section of the editor.

Explorer

The Explorer is a tool used to browse, open, and operate all of the files and folders in your editing project. Since VS Code is file- and folder-based, you can get started at any time simply by opening a file or folder in VS Code. Once you open a folder in VS Code, the contents of the folder are shown in the Explorer. You can do many modifications from here, such as:
  • Create, delete, and rename files and folders.

  • Change the location of files and folders by using drag and drop.

  • See the context menu to see all options.

Moreover, you can drag and drop files into the Explorer from outside VS Code to make a VS copy of them, so that if the explorer is empty, VS Code will access them instead.

VS Code also works very well with other tools that you might use, especially command-line tools. If you need to run a command-line tool in the context of the folder you have open in VS Code, right-click the folder and select Open in Command Prompt (or Open in Terminal on macOS or Linux).

At the same time, you can 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). You may also type Ctrl+P (Quick Open option) to quickly search and open a file by its name.

By default, VS Code does not open some folders from the Explorer (for example, .git). In this case, you can use the files.exclude setting to edit rules for hiding files and folders from the Explorer. However, if you have any derived resource files, such as *.meta in Unity or *.js in a TypeScript project, then this solution is not really going to be useful. Please note that for Unity to exclude the *.cs.metafiles, the pattern to select would be “**/*.cs.meta”: true. For TypeScript, you can exclude generated JavaScript for TypeScript files with “**/*.js”: {“when”: “$(basename).ts”}.

Multiselection

You can choose multiple files in the File Explorer and OPEN EDITORS view to complete actions (Delete, Drag and Drop, Open to the Side) on multiple items. Simply use the Ctrl/Cmd key with a 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 differentiate the two files. Also, remember that 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 feature, you can use the workbench.list.multiSelectModifier setting to modify multiselection to use the Alt key by “workbench.list.multiSelectModifier”: “alt”.

Filtering the Document Tree

It is possible to filter the currently visible files in the File Explorer. You can simply start typing part of the file name you want to match, keeping the focus on the File Explorer. You will be able to see a filter box in the top-right of the File Explorer presenting what you have typed so far, and matching file names will be highlighted. Once you press the cursor keys to move up and down the file list, it will switch between matching files or folders. However, switching over the filter box and selecting Enable Filter on Type will show only matching files and folders. You can apply the X Clear button to clear the filter.

Outline View

The Outline view is a section at the bottom of the File Explorer. When activated, it will show the symbol tree of the currently active editor. The Outline view has different Sort By modes and optional cursor tracking, and supports the usual open gestures. It also has an input box that can search for filters and symbols as you type. Errors and warnings are also displayed in the Outline view, allowing you to see a glimpse of a problem as well as its location.

As for symbols, the view relies heavily on the data computed by your installed extensions for different file types. For instance, the built-in Markdown support returns the Markdown header hierarchy for a Markdown file’s symbols.

Markdown Outline View

There are a few Outline view settings that allow you to enable and disable items and operate with errors and warnings display (all enabled by default):1
  • outline.icons: toggle rendering outline elements with icons.

  • outline.problems.enabled: shows errors and warnings on outline elements.

  • outline.problems.badges: toggle using badges for errors and warnings.

  • outline.problems.colors: toggle using colors for errors and warnings.

Open Editors

At the top of the Explorer, there is a section labeled as OPEN EDITORS that displays a list of active files or previews. There might also be some files visible that you previously opened in VS Code. For example, a file will be listed in the OPEN EDITORS view if you make a change to a file, double-click a file’s header, double-click a file in the Explorer, or open a file that is not part of the current folder. By clicking an item in the OPEN EDITORS view, it becomes active in VS Code. Once you are finished with your project and wish to remove files individually from the OPEN EDITORS view, or remove all files, you can do so by using the View: Close All Editors or View and then Close All Editors in Group actions.

Views

The File Explorer is just one of the Views available in VS Code. There are also Views for:2
  • Search: Provides global search and replace across your open folder.

  • Source Control: VS Code includes Git source control by default.

  • Run: VS Code’s Run and Debug View displays variables, call stacks, and breakpoints.

  • Extensions: Installs and manages your extensions within VS Code.

  • Custom views: Views contributed by extensions.

Any of these views can be accessed by using the View: Open View command.

Activity Bar

The Activity Bar on your left is designed for you to easily switch between Views. You can also reorder Views by dragging and dropping them on the Activity Bar, or stow away a View entirely with the right-click Hide from Activity Bar.

Command Palette

VS Code is also easily accessible from the keyboard. The most useful key combination to know is Ctrl+Shift+P, which calls for the Command Palette. With the Command Palette you have access to all of the functionality of VS Code, including keyboard shortcuts for the most implemented operations. The Command Palette provides access to many commands. You can manage editor commands, open files, search for items, and see a quick outline of a file, all while using the same interactive window. Following are a few navigation combinations:3
  • Ctrl+P will let you navigate to any file or symbol by typing its name.

  • Ctrl+Tab will cycle you through the last set of files opened.

  • Ctrl+Shift+P will bring you directly to the editor commands.

  • Ctrl+Shift+O will let you navigate to a specific symbol in a file.

  • Ctrl+G will let you navigate to a specific line in a file.

  • Type ? into the input field to get a list of available commands you can execute from Quick Open Help.

Configuring the Editor

VS Code has many options for you to configure the editor. From the View menu you can hide or toggle various bits of the user interface, such as the Side Bar, Status Bar, and Activity Bar.

Hiding the Menu Bar (for Windows, Linux)

You can hide the Menu Bar on Windows and Linux by selecting the setting window.menuBarVisibility from classic to toggle. The toggle setting means that a single press of the Alt key will show the Menu Bar again.

You can also remove the Menu Bar on Windows and Linux with the View ➤ Toggle Menu Bar command. This command switches window.menuBarVisibility from classic to compact, resulting in the Menu Bar moving into the Activity Bar. To move back to the Menu Bar to the classic position, select the View ➤ Toggle Menu Bar command again.

Settings

Most basic editor configurations are kept in settings that can be modified directly. You can set options globally through user settings, or per project or file through workspace settings. Settings options are kept in a settings.json file. You can follow the path Select File ➤ Preferences ➤ Settings (or press Ctrl+,) to edit the user settings.json file. To change workspace settings, click the WORKSPACE SETTINGS tab to edit the workspace settings.json file. Note that for macOS users, the Preferences menu is located under Code, not File; please follow Code ➤ Preferences ➤ Settings.

You can access the VS Code Default Settings in the left window, and your editable settings.json on the right. It is also possible to easily filter settings in the Default Settings using the search box at the top. You can 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 let you select a primary value as a section of their edit icon menu. After editing your settings, type Ctrl+S to settle your changes. The changes will take effect instantly. Workspace settings will override User settings and are beneficial for sharing particular project settings.

Zen Mode

Zen mode enables you to focus on your code by removing all User Interface items (Activity Bar, Status Bar, Side Bar, and Panel) except the editor, displaying the full screen and centering the editor layout only. Zen mode can be toggled using the View menu, Command Palette or by the shortcut, Ctrl+K Z. To exit Zen mode, press double Esc. The transition to full screen can be disabled via zenMode.fullScreen. Zen mode can be further modified using the following settings: zenMode.hideStatusBar, zenMode.hideTabs, zenMode.fullScreen, zenMode.restore, and zenMode.centerLayout.

Centered Editor Layout

Centered editor layout lets you center-align the editor area. This is especially useful if you find yourself working with a single editor on a large monitor. You can apply the sashes on the side to resize the view with the Alt key, and using the same method you can also independently move the sashes.

Tabs

VS Code displays open items with tabbed headings or Tabs in the title area above the editor. If you open a file, a new Tab is added for that file. Tabs allow you to quickly navigate between files, and you can drag and drop tabs to reorder them as you wish. When you have more open items than can fit in the title area, you can apply the Show Opened Editors command to show a dropdown list of tabbed items.

If you do not want to use Tabs, you can turn off the feature by setting the workbench.editor.showTabs setting to false: “workbench.editor.showTabs”: false.

Tab Ordering

By default, new Tabs are included to the right of the existing Tabs, but you can administer where you would like new Tabs to appear with the workbench.editor.openPositioning setting. For instance, you might like new tabbed items to appear on the left, by using “workbench.editor.openPositioning”: “left”.

Preview Mode

Once you single-click or select a file in the Explorer, it is shown in a presentation mode and reuses an existing Tab. This is particularly helpful if you just need to quickly browse files and do not want each file you accessed 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 assigned to that file. Preview mode is indicated by italics in the Tab heading: preview mode.

If you would rather not see the preview mode and always make a new Tab, you can control the pattern with these settings:
  • workbench.editor.enablePreview: to globally enable or disable preview editors.

  • workbench.editor.enablePreviewFromQuickOpen: to enable or disable preview editors when opened from Quick Open.

Editor Groups

If you split an editor via the Split Editor or Open to the Side commands, a new editor region that can hold a group of items is created instead. At the same time, you can open as many editor regions as you like side-by-side vertically and horizontally. You can see them in order in the OPEN EDITORS section at the top of the Explorer view. The OPEN EDITORS section also allows you to Drag and Drop editor groups on the workbench, move individual Tabs between groups, and quickly close entire groups by clicking on Close All.

Be sure that VS Code uses editor groups whether or not you have any Tabs on. Without Tabs, editor groups are a stack of your open items with the most recently searched item visible in the editor pane. By default, editor groups are structured in vertical columns when you split an editor to open it to the side. You can also arrange editor groups in any layout you like, both vertically and horizontally.

In order to support flexible layouts, you should create empty editor groups. By default, closing the last editor of an editor group will also close the group itself, but you can modify this behavior with the new setting workbench.editor.closeEmptyGroups: false. You can also see if there are any predefined set of editor layouts in the View ➤ Editor Layout menu.

Editors that open to the side by clicking the editor toolbar Split Editor action will normally open to the right-hand side of the active editor. If you prefer to open editors below the active one, configure the new setting workbench.editor.openSideBySideDirection: down.

There are plenty of keyboard commands for adjusting the editor layout with the keyboard alone, but if you prefer to use the mouse, drag and drop is the fastest method to split the editor into any direction. In addition, if you press and hold the Alt key while switching over the toolbar action to split an editor, it will offer to split to the other orientation. This is another fast way to split either to the right or to the bottom.

Keyboard Shortcuts

It will also be very beneficial for you to know some handy keyboard shortcuts to quickly navigate between editors and editor groups. Some of the most widely used ones are the following:4
  • Ctrl+PageDown go to the right editor.

  • Ctrl+PageUp go to the left editor.

  • Ctrl+Tab open the previous editor in the editor group MRU list.

  • Ctrl+1 go to the leftmost editor group.

  • Ctrl+2 go to the center editor group.

  • Ctrl+3 go to the rightmost editor group.

  • Ctrl+F4 close the active editor.

  • Ctrl+K W close all editors in the editor group.

  • Ctrl+K Ctrl+W close all editors.

Disabling Preview Mode

Without Tabs, the OPEN EDITORS section of the File Explorer is a great way to do file navigation. With preview editor mode, files are not shown in the OPEN EDITOR list, nor editor group on single-click open. You can turn this feature off through the workbench.editor.enablePreview and workbench.editor.enablePreviewFromQuickOpen settings.

Using Ctrl+Tab to Navigate in Entire Editor History

You can edit keybindings for Ctrl+Tab to show you a list of all opened editors from the history independent from the active editor group. You can edit your keybindings and add the following by using:
{ "key": "ctrl+tab", "command": "workbench.action.openPreviousEditorFromHistory" },
{ "key": "ctrl+tab", "command": "workbench.action.quickOpenNavigateNext", "when": "inQuickOpen" }

Closing an Entire Group Instead of a Single Editor

If you want to repeat the behavior of VS Code closing an entire group when closing one editor, you can bind the following in your keybindings by using:
macOS: { "key": "cmd+w", "command": "workbench.action.closeEditorsInGroup" }
Windows/Linux: { "key": "ctrl+w", "command": "workbench.action.closeEditorsInGroup" }

Window Management

VS Code has some options to operate to determine how windows can be opened or restored between sessions. The settings window.openFoldersInNewWindow and window.openFilesInNewWindow are used to configure opening new windows or reusing the last active window for files or folders and possible values by default.

If edited to turn to default conditions, VS Code will restore all windows you worked on during your previous session. However, there can still be cases where this setting is ignored (for instance, if using the -new-window or -reuse-window command-line option).

The window.restoreWindows setting tells VS Code how to restore the opened windows of your previous session. You can also change this setting to never reopen any windows and always start with an empty VS Code instance.

We will now take a look at how to set up VS Code for Python development.

Setting Up Visual Studio Code

Getting and activating VS Code is easy and quick. All it takes is a small download and then you can install it in a matter of minutes (Figure 1-2).
../images/514155_1_En_1_Chapter/514155_1_En_1_Fig2_HTML.jpg
Figure 1-2

Setting up VS Code

Cross-Platform

VS Code is a free code editor that runs on the macOS, Linux, and Windows operating systems.

For smoother installation you can follow the following platform-specific guides:5

MacOS

  1. 1.

    Download VS Code for macOS.

     
  2. 2.

    Open the browser’s download list and locate the downloaded archive.

     
  3. 3.

    Select the magnifying glass icon to open the archive in Finder.

     
  4. 4.

    Drag VS Code.app to the Applications folder, making it available in the macOS Launchpad.

     
  5. 5.

    Add VS Code to your Dock by right-clicking on the icon to bring up the context menu and choosing Options, Keep in Dock.

     

Linux

VS Code is officially distributed as a Snap package in the Snap Store, and can also be downloaded from the official site as an RPM or DEB package.

You can install it by running: sudo snap install --classic code # or code-insiders.

Once installed, the Snap daemon will take care of automatically updating VS Code in the background. You can also expect to get an in-product update notification whenever a new update is available.

Windows

  1. 1.

    Download the VS Code installer for Windows.

     
  2. 2.

    Once it is downloaded, run the installer (VSCodeUserSetup-{version}.exe). This will only take a minute.

     
  3. 3.

    By default, VS Code is installed under C:users{username}AppDataLocalProgramsMicrosoft VS Code.

     

VS Code is lightweight and should run on most available hardware and platform versions. You can review the System Requirements to see whether your computer configuration is supported.

Updating Cadence

VS Code releases a new version every month with new features and progressive bug fixes. Most platforms have auto-updating installed, so you will be prompted to look for the new release when it becomes available. You can also manually check for updates by running Help ➤ Check for Updates on Linux and Windows, or running Code ➤ Check for Updates on macOS. Additionally, you can also disable auto-update if you would like to update VS Code according to your own schedule.

Insiders Nightly Build

If you’d like to check out VS Code nightly builds to get access to new features earlier than the rest of the users or to verify bug fixes, you can install the Insiders build. The Insiders build installs side by side with the monthly Stable build, and you can freely incorporate and work with both on the same machine. The Insiders build is the same tool that the VS Code development team uses on a daily basis. If you have valuable feedback about the new features to offer, the development team would really appreciate it.

Portable Mode

VS Code also supports Portable mode installation. This mode ensures that all data created and maintained by VS Code is stored in close quarters so that when necessary it can be moved around across environments, even on a USB drive.

Additional Components

VS Code is an editor with a relatively small footprint. Unlike other traditional editors that tend to include every other function, with VS Code you can tune and customize your installation to the development technologies most important to you.

Extensions

VS Code extensions let third parties add support for the following:
  • Languages: C++, C#, Go, Java, Python

  • Tools: ESLint, JSHint , PowerShell

  • Debuggers: PHP XDebug

  • Keymaps: Vim, Sublime Text, IntelliJ, Emacs, Atom, Brackets, Visual Studio, Eclipse

Extensions smoothly integrate into VS Code’s User Interface, commands, and task running systems, so you will find it easy to operate with different technologies through VS Code’s shared interface.

Key Bindings for Visual Studio Code

VS Code offers you an option to manage most tasks directly from the keyboard (Figure 1-3). This section lists out the default bindings (keyboard shortcuts) and gives you an overview of how you can update them.
../images/514155_1_En_1_Chapter/514155_1_En_1_Fig3_HTML.jpg
Figure 1-3

Using keyboard shortcuts in VS Code

Keyboard Shortcuts Editor

VS Code has many simple keyboard shortcuts using Keyboard Shortcuts editor. It illustrates all available commands with and without keybindings, and you can easily change, remove, and update these using the available options. It also has a search box on the top that is useful when searching for commands or keybindings. You can open this editor by looking at the menu under File ➤ Preferences ➤ Keyboard Shortcuts (Code ➤ Preferences ➤ Keyboard Shortcuts on macOS). You can also access a printable version of these keyboard shortcuts at Help ➤ Keyboard Shortcut Reference and get a condensed PDF version suitable for printing as a user-friendly reference.

Detecting Keybinding Conflicts

If you have too many extensions installed or you have customized most of your keyboard shortcuts, you may at times face keybinding conflicts where the same keyboard shortcut is mapped to perform several commands. This can result in confusing occurrences, especially if different keybindings are going in and out of scope when you keep working with the editor. From time to time you should check on the Keyboard Shortcuts editor that has a context menu command Show Same Keybindings, which is used to filter the keybindings based on a keyboard shortcut to display and potentially prevent any conflicts.

Troubleshooting Keybindings

To troubleshoot keybindings problems, you can activate the command Developer: Toggle Keyboard Shortcuts Troubleshooting. This will help to perform logging of dispatched keyboard shortcuts and will give access to the output panel with the corresponding log file.

With it, you can later press your desired keybinding and check what keyboard shortcut VS Code uses and what command is activated.

Keyboard Rules

Each rule consists of the following:6
  • a key that defines the pressed keys.

  • a command containing the identifier of the command to execute.

  • an optional when clause containing a Boolean expression that will be calculated depending on the current context.

Two separate keypress actions known as Chords are described by separating the two keypresses with space. For example, Ctrl+K Ctrl+C.

When a key is pressed:
  • the rules are assessed from bottom to top.

  • the first rule that matches, both the key and in terms of when is accepted.

  • no more rules are processed.

  • if a rule is found and has a command set too, the command is implemented.

The additional keybindings.json rules are omitted at runtime to the bottom of the default rules, therefore allowing them to overwrite the default rules. The keybindings.json file is observed by VS Code, so editing it while VS Code is running will upgrade the rules at runtime.

The keyboard shortcuts dispatching is completed by analyzing a list of rules that are stored in JSON. To illustrate with a few examples:7
// Keybindings that are active when the focus is in the editor:
{ "key": "home",            "command": "cursorHome",              "when": "editorTextFocus" },
{ "key": "shift+home",      "command": "cursorHomeSelect",            "when": "editorTextFocus" },
// Keybindings that are complementary:
{ "key": "f5",              "command": "workbench.action.debug.continue", "when": "inDebugMode" },
{ "key": "f5",              "command": "workbench.action.debug.start",    "when": "!inDebugMode" },
// Global keybindings:
{ "key": "ctrl+f",          "command": "actions.find" },
{ "key": "alt+left",        "command": "workbench.action.navigateBack" },
{ "key": "alt+right",       "command": "workbench.action.navigateForward" },
// Global keybindings using chords (two separate keypress actions):
{ "key": "ctrl+k enter",    "command": "workbench.action.keepEditor" },
{ "key": "ctrl+k ctrl+w",   "command": "workbench.action.closeAllEditors" },

Accepted Keys

The key is made up of modifiers and the key itself. The following modifiers are accepted:

Platform

Modifiers

macOS

Ctrl+, Shift+, Alt+, Cmd+

Windows

Ctrl+, Shift+, Alt+, Win+

Linux

Ctrl+, Shift+, Alt+, Meta+

The following keys are accepted:
  • f1-f19, a-z, 0-9

  • `, -, =, [, ], , ;, ’, ,, ., /

  • left, up, right, down, pageup, pagedown, end, home

  • tab, enter, escape, space, backspace, delete

  • pausebreak, capslock, insert

  • numpad0-numpad9, numpad_multiply, numpad_add, numpad_separator

  • numpad_subtract, numpad_decimal, numpad_divide

Command Arguments

You can call on command with arguments. This is especially helpful if you usually perform the same operation on a specific file or folder. You can include a custom keyboard shortcut to do exactly what you need it to do. The following is an example of overriding the Enter key to print some text:
{
  "key": "enter",
  "command": "type",
  "args": { "text": "Hello There" },
  "when": "editorTextFocus"
}

The type command will receive {“text”: “Hello There”} as its first argument and add “Hello There” to the file instead of producing the default command.

Removing a Specific Key Binding Rule

You can script a key binding rule that targets the dismissal of a specific default key binding. With keybindings.json it was always acceptable to redefine all the key bindings of VS Code, but it can be challenging to make a small addition, especially around overloaded keys, such as Tab or Escape. In order to hide a specific key binding, add a - to the command and the rule will be a removal one.

Keyboard Layout-Independent Nindings

Using scan codes, it is manageable to define keybindings that do not change with the modification of the keyboard layout. For example: { “key”: “cmd+[Slash]”, “command”: “editor.action.commentLine”, and “when”: “editorTextFocus” }.

The following scan codes are accepted:
[F1]-[F19], [KeyA]-[KeyZ], [Digit0]-[Digit9]
[Backquote], [Minus], [Equal], [BracketLeft], [BracketRight], [Backslash], [Semicolon], [Quote], [Comma], [Period], [Slash]
[ArrowLeft], [ArrowUp], [ArrowRight], [ArrowDown], [PageUp], [PageDown], [End], [Home]
[Tab], [Enter], [Escape], [Space], [Backspace], [Delete]
[Pause], [CapsLock], [Insert]
[Numpad0]-[Numpad9], [NumpadMultiply], [NumpadAdd], [NumpadComma]
[NumpadSubtract], [NumpadDecimal], [NumpadDivide]

When Clause Contexts

VS Code gives you full control over when your key bindings are activated through the optional when clause. If some key bindings do not have a when clause, those key binding are globally available at all times. A when clause relates to either Boolean true or false for operating key bindings.

In addition, VS Code sets various context keys and specific values depending on what elements are available and active in the VS Code User Interface. For instance, the built-in Start Debugging command has the keyboard shortcut F5, which is only enabled when there is an appropriate debugger available (context debuggersAvailable is true) and the editor is not in debug mode (context inDebugMode is false).

Conditional Operators

For when clause conditional expressions, the conditional operators in Table 1-1 are used for keybindings.8
Table 1-1

Conditional operators

Operator

Symbol

Example

Equality

==

“editorLangId == typescript”

Inequality

!=

“resourceExtname != .js”

Or

||

“isLinux||isWindows”

And

&&

“textInputFocus && !editorReadonly”

Matches

=~

“resourceScheme =~ /^untitled$|^file$/”

Available Contexts

You can see some of the available contexts at hand when clause contexts in the when clause context reference. The list there is not as exhaustive, and you can look for other when clause contexts by searching and filtering in the Keyboard Shortcuts editor (Preferences: Open Keyboard Shortcuts) or reviewing the Default Keybindings JSON file (Preferences: Open Default Keyboard Shortcuts (JSON)). Tables 1-2 through 1-12 provides shortcuts for some basic commands.9
Table 1-2

Basic editing

Command

Key

Command id

Cut line (empty selection)

Ctrl+X

editor.action.clipboardCutAction

Copy line (empty selection)

Ctrl+C

editor.action.clipboardCopyAction

Paste

Ctrl+V

editor.action.clipboardPasteAction

Delete Line

Ctrl+Shift+K

editor.action.deleteLines

Insert Line Below

Ctrl+Enter

editor.action.insertLineAfter

Insert Line Above

Ctrl+Shift+Enter

editor.action.insertLineBefore

Move Line Down

Alt+Down

editor.action.moveLinesDownAction

Move Line Up

Alt+Up

editor.action.moveLinesUpAction

Copy Line Down

Shift+Alt+Down

editor.action.copyLinesDownAction

Copy Line Up

Shift+Alt+Up

editor.action.copyLinesUpAction

Undo

Ctrl+Z

undo

Redo

Ctrl+Y

redo

Add Selection To Next Find Match

Ctrl+D

editor.action.addSelectionToNextFindMatch

Move Last Selection To Next Find Match

Ctrl+K

editor.action.moveSelectionToNextFindMatch

Undo last cursor operation

Ctrl+U

cursorUndo

Insert cursor at end of line

Shift+Alt+I

editor.action.insertCursorAtEndOfEachLineSelected

Select all occurrences of current selection

Ctrl+Shift+L

editor.action.selectHighlights

Select all occurrences of current word

Ctrl+F2

editor.action.changeAll

Select current line

Ctrl+L

expandLineSelection

Insert Cursor Below

Ctrl+Alt+Down

editor.action.insertCursorBelow

Insert Cursor Above

Ctrl+Alt+Up

editor.action.insertCursorAbove

Jump to matching bracket

Ctrl+Shift+

editor.action.jumpToBracket

Indent Line

Ctrl+]

editor.action.indentLines

Outdent Line

Ctrl+[

editor.action.outdentLines

Go to Beginning of Line

Home

cursorHome

Go to End of Line

End

cursorEnd

Go to End of File

Ctrl+End

cursorBottom

Go to Beginning of File

Ctrl+Home

cursorTop

Scroll Line Down

Ctrl+Down

scrollLineDown

Scroll Line Up

Ctrl+Up

scrollLineUp

Scroll Page Down

Alt+PageDown

scrollPageDown

Scroll Page Up

Alt+PageUp

scrollPageUp

Fold (collapse) region

Ctrl+Shift+[

editor.fold

Unfold (uncollapse) region

Ctrl+Shift+]

editor.unfold

Fold (collapse) all subregions

Ctrl+K Ctrl+[

editor.foldRecursively

Unfold (uncollapse) all subregions

Ctrl+K Ctrl+]

editor.unfoldRecursively

Fold (collapse) all regions

Ctrl+K Ctrl+0

editor.foldAll

Unfold (uncollapse) all regions

Ctrl+K Ctrl+J

editor.unfoldAll

Add Line Comment

Ctrl+K Ctrl+C

editor.action.addCommentLine

Remove Line Comment

Ctrl+K Ctrl+U

editor.action.removeCommentLine

Toggle Line Comment

Ctrl+/

editor.action.commentLine

Toggle Block Comment

Shift+Alt+A

editor.action.blockComment

Find

Ctrl+F

actions.find

Replace

Ctrl+H

editor.action.startFindReplaceAction

Find Next

Enter

editor.action.nextMatchFindAction

Find Previous

Shift+Enter

editor.action.previousMatchFindAction

Select All Occurrences of Find Match

Alt+Enter

editor.action.selectAllMatches

Toggle Find Case Sensitive

Alt+C

toggleFindCaseSensitive

Toggle Find Regex

Alt+R

toggleFindRegex

Toggle Find Whole Word

Alt+W

toggleFindWholeWord

Toggle Use of Tab Key for Setting Focus

Ctrl+M

editor.action.toggleTabFocusMode

Toggle Render Whitespace

unassigned

toggleRenderWhitespace

Toggle Word Wrap

Alt+Z

editor.action.toggleWordWrap

Table 1-3

Rich languages editing

Command

Key

Command id

Trigger Suggest

Ctrl+Space

editor.action.triggerSuggest

Trigger Parameter Hints

Ctrl+Shift+Space

editor.action.triggerParameterHints

Format Document

Shift+Alt+F

editor.action.formatDocument

Format Selection

Ctrl+K Ctrl+F

editor.action.formatSelection

Go to Definition

F12

editor.action.revealDefinition

Show Hover

Ctrl+K Ctrl+I

editor.action.showHover

Peek Definition

Alt+F12

editor.action.peekDefinition

Open Definition to the Side

Ctrl+K F12

editor.action.revealDefinitionAside

Quick Fix

Ctrl+.

editor.action.quickFix

Go to References

Shift+F12

editor.action.goToReferences

Rename Symbol

F2

editor.action.rename

Replace with Next Value

Ctrl+Shift+.

editor.action.inPlaceReplace.down

Replace with Previous Value

Ctrl+Shift+,

editor.action.inPlaceReplace.up

Expand AST Selection

Shift+Alt+Right

editor.action.smartSelect.expand

Shrink AST Selection

Shift+Alt+Left

editor.action.smartSelect.shrink

Trim Trailing Whitespace

Ctrl+K Ctrl+X

editor.action.trimTrailingWhitespace

Change Language Mode

Ctrl+K M

workbench.action.editor.changeLanguageMode

Table 1-4

Navigation

Command

Key

Command id

Show All Symbols

Ctrl+T

workbench.action.showAllSymbols

Go to Line...

Ctrl+G

workbench.action.gotoLine

Go to File..., Quick Open

Ctrl+P

workbench.action.quickOpen

Go to Symbol...

Ctrl+Shift+O

workbench.action.gotoSymbol

Show Problems

Ctrl+Shift+M

workbench.actions.view.problems

Go to Next Error or Warning

F8

editor.action.marker.nextInFiles

Go to Previous Error or Warning

Shift+F8

editor.action.marker.prevInFiles

Show All Commands

Ctrl+Shift+P or F1

workbench.action.showCommands

Navigate Editor History

Ctrl+Tab

workbench.action.quickOpenPreviousRecentlyUsedEditorInGroup

Go Back

Alt+Left

workbench.action.navigateBack

Go back in Quick Input

Alt+Left

workbench.action.quickInputBack

Go Forward

Alt+Right

workbench.action.navigateForward

Table 1-5

Editor/window management

Command

Key

Command id

New Window

Ctrl+Shift+N

workbench.action.newWindow

Close Window

Ctrl+W

workbench.action.closeWindow

Close Editor

Ctrl+F4

workbench.action.closeActiveEditor

Close Folder

Ctrl+K F

workbench.action.closeFolder

Cycle Between Editor Groups

unassigned

workbench.action.navigateEditorGroups

Split Editor

Ctrl+

workbench.action.splitEditor

Focus into First Editor Group

Ctrl+1

workbench.action.focusFirstEditorGroup

Focus into Second Editor Group

Ctrl+2

workbench.action.focusSecondEditorGroup

Focus into Third Editor Group

Ctrl+3

workbench.action.focusThirdEditorGroup

Focus into Editor Group on the Left

unassigned

workbench.action.focusPreviousGroup

Focus into Editor Group on the Right

unassigned

workbench.action.focusNextGroup

Move Editor Left

Ctrl+Shift+PageUp

workbench.action.moveEditorLeftInGroup

Move Editor Right

Ctrl+Shift+PageDown

workbench.action.moveEditorRightInGroup

Move Active Editor Group Left

Ctrl+K Left

workbench.action.moveActiveEditorGroupLeft

Move Active Editor Group Right

Ctrl+K Right

workbench.action.moveActiveEditorGroupRight

Move Editor into Next Group

Ctrl+Alt+Right

workbench.action.moveEditorToNextGroup

Move Editor into Previous Group

Ctrl+Alt+Left

workbench.action.moveEditorToPreviousGroup

Table 1-6

File management

Command

Key

Command id

New File

Ctrl+N

workbench.action.files.newUntitledFile

Open File...

Ctrl+O

workbench.action.files.openFile

Save

Ctrl+S

workbench.action.files.save

Save All

Ctrl+K S

saveAll

Save As...

Ctrl+Shift+S

workbench.action.files.saveAs

Close

Ctrl+F4

workbench.action.closeActiveEditor

Close Others

unassigned

workbench.action.closeOtherEditors

Close Group

Ctrl+K W

workbench.action.closeEditorsInGroup

Close Other Groups

unassigned

workbench.action.closeEditorsInOtherGroups

Close Group to Left

unassigned

workbench.action.closeEditorsToTheLeft

Close Group to Right

unassigned

workbench.action.closeEditorsToTheRight

Close All

Ctrl+K Ctrl+W

workbench.action.closeAllEditors

Reopen Closed Editor

Ctrl+Shift+T

workbench.action.reopenClosedEditor

Keep Open

Ctrl+K Enter

workbench.action.keepEditor

Copy Path of Active File

Ctrl+K P

workbench.action.files.copyPathOfActiveFile

Reveal Active File in Window

Ctrl+K R

workbench.action.files.revealActiveFileInWindows

Show Opened File in New Window

Ctrl+K

workbench.action.files.showOpenedFileInNewWindow

Compare Opened File With

unassigned

workbench.files.action.compareFileWith

Table 1-7

Display

Command

Key

Command id

Toggle Full Screen

F11

workbench.action.toggleFullScreen

Toggle Zen Mode

Ctrl+K Z

workbench.action.toggleZenMode

Leave Zen Mode

Escape

workbench.action.exitZenMode

Zoom in

Ctrl+=

workbench.action.zoomIn

Zoom out

Ctrl+-

workbench.action.zoomOut

Reset Zoom

Ctrl+Numpad0

workbench.action.zoomReset

Toggle Sidebar Visibility

Ctrl+B

workbench.action.toggleSidebarVisibility

Show Explorer / Toggle Focus

Ctrl+Shift+E

workbench.view.explorer

Show Search

Ctrl+Shift+F

workbench.view.search

Show Source Control

Ctrl+Shift+G

workbench.view.scm

Show Run

Ctrl+Shift+D

workbench.view.debug

Show Extensions

Ctrl+Shift+X

workbench.view.extensions

Show Output

Ctrl+Shift+U

workbench.action.output.toggleOutput

Quick Open View

Ctrl+Q

workbench.action.quickOpenView

Open New Command Prompt

Ctrl+Shift+C

workbench.action.terminal.openNativeConsole

Toggle Markdown Preview

Ctrl+Shift+V

markdown.showPreview

Open Preview to the Side

Ctrl+K V

markdown.showPreviewToSide

Toggle Integrated Terminal

Ctrl+`

workbench.action.terminal.toggleTerminal

Table 1-8

Search

Command

Key

Command id

Show Search

Ctrl+Shift+F

workbench.view.search

Replace in Files

Ctrl+Shift+H

workbench.action.replaceInFiles

Toggle Match Case

Alt+C

toggleSearchCaseSensitive

Toggle Match Whole Word

Alt+W

toggleSearchWholeWord

Toggle Use Regular Expression

Alt+R

toggleSearchRegex

Toggle Search Details

Ctrl+Shift+J

workbench.action.search.toggleQueryDetails

Focus Next Search Result

F4

search.action.focusNextSearchResult

Focus Previous Search Result

Shift+F4

search.action.focusPreviousSearchResult

Show Next Search Term

Down

history.showNext

Show Previous Search Term

Up

history.showPrevious

Table 1-9

Search editor

Command

Key

Command id

Open Results In Editor

Alt+Enter

search.action.openInEditor

Focus Search Editor Input

Escape

search.action.focusQueryEditorWidget

Search Again

Ctrl+Shift+R

rerunSearchEditorSearch

Delete File Results

Ctrl+Shift+Backspace

search.searchEditor.action.deleteFileResults

Table 1-10

Preferences

Command

Key

Command id

Open Settings

Ctrl+,

workbench.action.openSettings

Open Workspace Settings

unassigned

workbench.action.openWorkspaceSettings

Open Keyboard Shortcuts

Ctrl+K Ctrl+S

workbench.action.openGlobalKeybindings

Open User Snippets

unassigned

workbench.action.openSnippets

Select Color Theme

Ctrl+K Ctrl+T

workbench.action.selectTheme

Configure Display Language

unassigned

workbench.action.configureLocale

Table 1-11

Debug

Command

Key

Command id

Toggle Breakpoint

F9

editor.debug.action.toggleBreakpoint

Start

F5

workbench.action.debug.start

Continue

F5

workbench.action.debug.continue

Start (without debugging)

Ctrl+F5

workbench.action.debug.run

Pause

F6

workbench.action.debug.pause

Step Into

F11

workbench.action.debug.stepInto

Table 1-12

Tasks

Command

 

Key

Command id

Run Build Task

 

Ctrl+Shift+B

workbench.action.tasks.build

Run Test Task

 

Unassigned

workbench.action.tasks.test

Table 1-13

Extensions

Command

Key

Command id

Install Extension

unassigned

workbench.extensions.action.installExtension

Show Installed Extensions

unassigned

workbench.extensions.action.showInstalledExtensions

Show Outdated Extensions

unassigned

workbench.extensions.action.listOutdatedExtensions

Show Recommended Extensions

unassigned

workbench.extensions.action.showRecommendedExtensions

Show Popular Extensions

unassigned

workbench.extensions.action.showPopularExtensions

Update All Extensions

unassigned

workbench.extensions.action.updateAllExtensions

Programming Languages Supported

In VS Code, there is a support tool for almost every major programming language. Most of the default settings for JavaScript, TypeScript, CSS, and HTML with rich language extensions can be found in the VS Code Marketplace. These are eight of the most popular language extensions:
  • Python

  • C/C++

  • C#

  • Java Extension Pack

  • Go

  • Dart

  • PHP Extension Pack

  • Ruby

You can go to the Marketplace or check out the integrated Extensions view and search for your desired programming language to find snippets, code completion and IntelliSense providers, linters, debuggers, and more. If you want to change the display language of VS Code (for example, to some other available language), you can do that in the Display Language topic.

It is best to have some prior understanding of these programming languages and their language specific documentation supported by VS Code in advance.

Language Features in VS Code

The richness of support characteristics varies across the different languages and their extensions:
  • Syntax highlighting and bracket matching

  • Smart completions

  • Linting and corrections

  • Code navigation (Go to Definition, Find All References)

  • Debugging

  • Refactoring

Changing the Language for the Selected File

In VS Code, there is a default setting of the language support for a file based on its filename extension. Nevertheless, when you need to change a few language modes, you can do so by clicking on the language indicator, which is located on the right-hand side of the Status Bar. This will call up the Select Language Mode dropdown, where you can see and choose another language for the current file.

Additional Components and Tools

VS Code is quite minimal by design and only includes the limited number of components shared across most development platforms. Basic functionality such as the editor, file management, window management, and preference settings are included. A JavaScript and TypeScript language service and Node.js debugger are also part of the basic structure.

If you are used to working with bigger, more inclusive, and diverse development tools, you may be surprised that your scenarios are not always fully supported out of the box. For instance, there is not a File ➤ New Project dialog with preinstalled project templates. Most VS Code users will be required to look for and download additional components, depending on their specific projects.

Commonly Used Components

Here are a few commonly installed components:
  • Git: VS Code has built-in support for source code control using Git, but needs Git to be installed on the side.

  • Node.js (includes npm): A cross-platform mostly used for building and running JavaScript applications.

  • TypeScript: The TypeScript compiler, tsc, for transcripting TypeScript to JavaScript.

VS Code Extensions

You can also expand the VS Code editor itself through extensions. The VS Code community has built the multiple varieties of useful extensions available on the VS Code Marketplace for the following programming languages:
  • Python

  • C/C++

  • Jupyter

  • ESLint

  • Prettier: code formatter

  • Live Server

  • Visual Studio IntelliCode

  • C#

Additional Tools

VS Code effectively integrates with some widely used toolchains. The following tools will assist in advancing your development experience:
  • Yeoman: an application scaffolding tool, a command-line version of File ➤ New Project.

  • generator-aspnet: a Yeoman generator for running ASP.NET Core applications.

  • generator-hot towel: a Yeoman generator for easy creation of AngularJS applications.

  • Express: an application framework for Node.js applications using the Pug template engine.

  • Gulp: a streaming task runner system that could be incorporated with VS Code tasks.

  • Mocha: a JavaScript test framework that runs on Node.js.

  • Yarn: a dependency manager and a good alternative to npm.

Please note that most of these tools require Node.js and the npm package manager to download and apply.

Settings Precedence

Configurations can be overridden at multiple levels by the different setting scopes:
  • User settings: applies globally to all VS Code instances.

  • Workspace setting: goes to the open folder or workspace and normally overrides User settings.

  • Workspace Folder settings: typically applies to a specific folder of a multiroot workspace; overrides both User and Workspace settings.

Setting values can be of various types:
  • String: “files.autoSave”: “afterDelay”

  • Boolean: “editor.minimap.enabled”: true

  • Number: “files.autoSaveDelay”: 1000

  • Array: “editor.rulers”: []

  • Object: “search.exclude”: { “**/node_modules”: true, “**/bower_components”: true }

Values with primitive types and Array type are overridden, but those with Object type are merged. For example, workbench.colorCustomizations takes an Object that specifies a group of User Interface items and their desired colors. If there are conflicting values, the usual reaction would be to override behavior with workspace values taking precedence over user values.

Settings and Security

Some settings let you specify an executable that VS Code will run to operate over certain operations. For example, you can select which shell the Integrated Terminal would be using. For more advanced security, such settings can only be determined in user settings and not at workspace scope. See the list of settings not supported in workspace settings:
  • git.path

  • terminal.external.windowsExec

  • terminal.external.osxExec

  • terminal.external.linuxExec

The first time you activate a workspace that determines any of these settings, VS Code is going to warn you once, and you may ignore the values after that.

Summary

In this chapter we have covered the basics related to VS Code, including its user interface and keyboard shortcuts.

In the next chapter we will look closer at the VS Code for Python Development, including the list of required extensions, linting, and debugging requirements.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.230.107