Basic Editing

Visual Studio Code is an editor first and foremost, and includes the features you need for highly productive source code editing. This topic takes you through the basics of the editor and helps you get moving with your code.

Keyboard shortcuts

Being able to keep your hands on the keyboard when writing code is crucial for high productivity. VS Code has a rich set of default keyboard shortcuts as well as allowing you to customize them.

Multiple selections (multi-cursor)

VS Code supports multiple cursors for fast simultaneous edits. You can add secondary cursors (rendered thinner) withAlt+Click.Each cursor operates independently based on the context it sits in. A common way to add more cursors is with⌥⌘↓(WindowsCtrl+Alt+Down,LinuxShift+Alt+Down)or⌥⌘↑(WindowsCtrl+Alt+Up,LinuxShift+Alt+Up)that insert cursors below or above.

Note:Your graphics card driver (for example NVIDIA) might overwrite these default shortcuts.

Multi-cursor

⌘D(Windows, LinuxCtrl+D)selects the word at the cursor, or the next occurrence of the current selection.

Multi-cursor-next-word

Tip:You can also add more cursors with⇧⌘L(Windows, LinuxCtrl+Shift+L),which will add a selection at each occurrence of the current selected text.

Multi-cursor modifier

If you'd like to change the modifier key for applying multiple cursors toCmd+Clickon macOS andCtrl+Clickon Windows and Linux, you can do so with theeditor.multiCursorModifiersetting.This lets users coming from other editors such as Sublime Text or Atom continue to use the keyboard modifier they are familiar with.

The setting can be set to:

  • ctrlCmd- Maps toCtrlon Windows andCmdon macOS.
  • alt- The existing defaultAlt.

There's also a menu itemSelection>Switch to Ctrl+Click for Multi-CursororSelection>Switch to Alt+Click for Multi-Cursorto quickly toggle this setting.

TheGo to DefinitionandOpen Linkgestures will also respect this setting and adapt such that they do not conflict. For example, when the setting isctrlCmd,multiple cursors can be added withCtrl/Cmd+Click,and opening links or going to definition can be invoked withAlt+Click.

Shrink/expand selection

Quickly shrink or expand the current selection. Trigger it with⌃⇧⌘←(Windows, LinuxShift+Alt+Left)and⌃⇧⌘→(Windows, LinuxShift+Alt+Right).

Here's an example of expanding the selection with⌃⇧⌘→(Windows, LinuxShift+Alt+Right):

Expand selection

Column (box) selection

Place the cursor in one corner and then holdShift+Altwhile dragging to the opposite corner:

Column text selection

Note: This changes toShift+Ctrl/Cmdwhen usingCtrl/Cmdasmulti-cursor modifier.

There are also default key bindings for column selection on macOS and Windows, but not on Linux.

Key Command Command ID
⇧↓(Windows, LinuxShift+Down) Column Select Down cursorColumnSelectDown
⇧↑(Windows, LinuxShift+Up) Column Select Up cursorColumnSelectUp
⇧←(Windows, LinuxShift+Left) Column Select Left cursorColumnSelectLeft
⇧→(Windows, LinuxShift+Right) Column Select Right cursorColumnSelectRight
⇧PageDown(Windows, LinuxShift+PageDown) Column Select Page Down cursorColumnSelectPageDown
⇧PageUp(Windows, LinuxShift+PageUp) Column Select Page Up cursorColumnSelectPageUp

You canedityourkeybindings.jsonto bind them to something more familiar if you want.

Column Selection mode

The user settingEditor: Column Selectioncontrols this feature. Once this mode is entered, as indicated in the Status bar, the mouse gestures and the arrow keys will create a column selection by default. This global toggle is also accessible via theSelection>Column Selection Modemenu item. In addition, one can also disable Column Selection mode from the Status bar.

Save / Auto Save

By default, VS Code requires an explicit action to save your changes to disk,⌘S(Windows, LinuxCtrl+S).

However, it's easy to turn onAuto Save,which will save your changes after a configured delay or when focus leaves the editor. With this option turned on, there is no need to explicitly save the file. The easiest way to turn onAuto Saveis with theFile>Auto Savetoggle that turns on and off save after a delay.

For more control overAuto Save,open User or Workspacesettingsand find the associated settings:

  • files.autoSave:Can have the values:
    • off- to disable auto save.
    • afterDelay- to save files after a configured delay (default 1000 ms).
    • onFocusChange- to save files when focus moves out of the editor of the dirty file.
    • onWindowChange- to save files when the focus moves out of the VS Code window.
  • files.autoSaveDelay:Configures the delay in milliseconds whenfiles.autoSaveis configured toafterDelay.The default is 1000 ms.

Hot Exit

By default, VS Code remembers unsaved changes to files when you exit. Hot exit is triggered when the application is closed viaFile>Exit(Code>Quiton macOS) or when the last window is closed.

You can configure hot exit by settingfiles.hotExitto the following values:

  • "off":Disable hot exit.
  • "onExit":Hot exit will be triggered when the application is closed, that is when the last window is closed on Windows/Linux or when theworkbench.action.quitcommand is triggered (from theCommand Palette,keyboard shortcut or menu). All windows without folders opened will be restored upon next launch.
  • "onExitAndWindowClose":Hot exit will be triggered when the application is closed, that is when the last window is closed on Windows/Linux or when theworkbench.action.quitcommand is triggered (from theCommand Palette,keyboard shortcut or menu), and also for any window with a folder opened regardless of whether it is the last window. All windows without folders opened will be restored upon next launch. To restore folder windows as they were before shutdown, setwindow.restoreWindowstoall.

If something goes wrong with hot exit, all backups are stored in the following folders for standard install locations:

  • Windows%APPDATA%\Code\Backups
  • macOS$HOME/Library/Application Support/Code/Backups
  • Linux$HOME/.config/Code/Backups

Find and Replace

VS Code allows you to quickly find text and replace in the currently opened file. Press⌘F(Windows, LinuxCtrl+F)to open the Find Widget in the editor, search results will be highlighted in the editor, overview ruler and minimap.

If there are more than one matched result in the current opened file, you can pressEnterand⇧Enter(Windows, LinuxShift+Enter)to navigate to next or previous result when the find input box is focused.

Seed Search String From Selection

When the Find Widget is opened, it will automatically populate the selected text in the editor into the find input box. If the selection is empty, the word under the cursor will be inserted into the input box instead.

Seed Search String From Selection

This feature can be turned off by settingeditor.find.seedSearchStringFromSelectionto"never".

Find In Selection

By default, the find operations are run on the entire file in the editor. It can also be run on selected text. You can turn this feature on by clicking the hamburger icon on the Find Widget.

Find In Selection

If you want it to be the default behavior of the Find Widget, you can seteditor.find.autoFindInSelectiontoalways,or tomultiline,if you want it to be run on selected text only when multiple lines of content are selected.

Advanced find and replace options

In addition to find and replace with plain text, the Find Widget also has three advanced search options:

  • Match Case
  • Match Whole Word
  • Regular Expression

The replace input box support case preserving, you can turn it on by clicking the Preserve Case (AB) button.

Multiline support and Find Widget resizing

You can search multiple line text by pasting the text into the Find input box and Replace input box. PressingCtrl+Enterinserts a new line in the input box.

Multiple Line Support

While searching long text, the default size of Find Widget might be too small. You can drag the left sash to enlarge the Find Widget or double click the left sash to maximize it or shrink it to its default size.

Resize Find Widget

Search across files

VS Code allows you to quickly search over all files in the currently opened folder. Press⇧⌘F(Windows, LinuxCtrl+Shift+F)and enter your search term. Search results are grouped into files containing the search term, with an indication of the hits in each file and its location. Expand a file to see a preview of all of the hits within that file. Then single-click on one of the hits to view it in the editor.

A simple text search across files

Tip:We support regular expression searching in the search box, too.

You can configure advanced search options by clicking the ellipsis (Toggle Search Details) below the search box on the right (or press⇧⌘J(Windows, LinuxCtrl+Shift+J)). This will show additional fields to configure the search.

Tip:You can use Quick Search to quickly find text across all files in the currently opened folder. Open the Command Palette (⇧⌘P(Windows, LinuxCtrl+Shift+P)) and enter theSearch: Quick Searchcommand.

Advanced search options

Advanced search options

In the two input boxes below the search box, you can enter patterns to include or exclude from the search. If you enterexample,that will match every folder and file namedexamplein the workspace. If you enter./example,that will match the folderexample/at the top level of your workspace. Use,to separate multiple patterns. Paths must use forward slashes. You can also useglob patternsyntax, for example:

  • *to match zero or more characters in a path segment
  • ?to match on one character in a path segment
  • **to match any number of path segments, including none
  • {}to group conditions (for example{**/*.html,**/*.txt}matches all HTML and text files)
  • []todeclarea range of characters to match (example.[0-9]to match onexample.0,example.1,…)
  • [!...]to negate a range of characters to match (example.[!0-9]to match onexample.a,example.b,but notexample.0)

VS Code excludes some folders by default to reduce the number of search results that you are not interested in (for example:node_modules). Opensettingsto change these rules under thefiles.excludeandsearch.excludesection.

Note that glob patterns in the Search view work differently than in settings such asfiles.excludeandsearch.exclude.In the settings, you must use**/exampleto match a folder namedexamplein subfolderfolder1/examplein your workspace. In the Search view, the**prefix is assumed. The glob patterns in these settings are always evaluated relative to the path of the workspace folder.

Also note theUse Exclude Settings and Ignore Filestoggle button in thefiles to excludebox. The toggle determines whether to exclude files that are ignored by your.gitignorefiles and/or matched by yourfiles.excludeandsearch.excludesettings.

Tip:From the Explorer, you can right-click on a folder and selectFind in Folderto search inside a folder only.

Search and replace

You can also Search and Replace across files. Expand the Search widget to display the Replace text box.

search and replace

When you type text into the Replace text box, you will see a diff display of the pending changes. You can replace across all files from the Replace text box, replace all in one file or replace a single change.

search and replace diff view

Tip:You can quickly reuse a previous search term by using(Windows, LinuxDown)and(Windows, LinuxUp)to navigate through your search term history.

Case changing in regex replace

VS Code supports changing the case of regex matching groups while doing Search and Replace in the editor or globally. This is done with the modifiers\u\U\l\L,where\uand\lwill upper/lowercase a single character, and\Uand\Lwill upper/lowercase the rest of the matching group.

Example:

Changing case while doing find and replace

The modifiers can also be stacked - for example,\u\u\u$1will uppercase the first three characters of the group, or\l\U$1will lowercase the first character, and uppercase the rest. The capture group is referenced by$nin the replacement string, wherenis the order of the capture group.

Search Editor

Search Editors let you view workspace search results in a full-sized editor, complete with syntax highlighting and optional lines of surrounding context.

Below is a search for the word 'SearchEditor' with two lines of text before and after the match for context:

Search Editor overview

TheOpen Search Editorcommand opens an existing Search Editor if one exists, or to otherwise create a new one. TheNew Search Editorcommand will always create a new Search Editor.

In the Search Editor, results can be navigated to usingGo to Definitionactions, such asF12to open the source location in the current editor group, or⌘K F12(Windows, LinuxCtrl+K F12)to open the location in an editor to the side. Additionally, you can configure the behavior for single-clicking or double-clicking a search result with thesearch.searchEditor.singleClickBehaviourandsearch.searchEditor.doubleClickBehavioursettings. For example, to open a peek definition window or to open the source location.

You can also use theOpen New Search Editorbutton at the top of the Search view, and can copy your existing results from a Search view over to a Search Editor with theOpen in editorlink at the top of the results tree, or theSearch Editor: Open Results in Editorcommand.

Search Editor Button

The Search Editor above was opened by selecting theOpen New Search Editorbutton (third button) on the top of the Search view.

Search Editor commands and arguments

  • search.action.openNewEditor- Opens the Search Editor in a new tab.
  • search.action.openInEditor- Copy the current Search results into a new Search Editor.
  • search.action.openNewEditorToSide- Opens the Search Editor in a new window next to the window you currently have opened.

There are two arguments that you can pass to the Search Editor commands (search.action.openNewEditor,search.action.openNewEditorToSide) to allow keybindings to configure how a new Search Editor should behave:

  • triggerSearch- Whether a search be automatically run when a Search Editor is opened. Default is true.
  • focusResults- Whether to put focus in the results of a search or the query input. Default is true.

For example, the following keybinding runs the search when the Search Editor is opened but leaves the focus in the search query control.

{
"key":"ctrl+o",
"command":"search.action.openNewEditor",
"args":{"query":"VS Code","triggerSearch":true,"focusResults":false}
}

Search Editor context default

Thesearch.searchEditor.defaultNumberOfContextLinessetting has a default value of 1, meaning one context line will be shown before and after each result line in the Search Editor.

Reuse last Search Editor configuration

Thesearch.searchEditor.reusePriorSearchConfigurationsetting (default isfalse) lets you reuse the last active Search Editor's configuration when creating a new Search Editor.

IntelliSense

We'll always offer word completion, but for the richlanguages,such as JavaScript, JSON, HTML, CSS, SCSS, Less, C# and TypeScript, we offer a true IntelliSense experience. If a language service knows possible completions, the IntelliSense suggestions will pop up as you type. You can always manually trigger it with⌃Space(Windows, LinuxCtrl+Space).By default,TaborEnterare the accept keyboard triggers but you can alsocustomize these key bindings.

Tip:The suggestions filtering supports CamelCase, so you can type the letters which are upper cased in a method name to limit the suggestions. For example, "cra" will quickly bring up "createApplication".

Tip:IntelliSense suggestions can be configured via theeditor.quickSuggestionsandeditor.suggestOnTriggerCharacterssettings.

JavaScript and TypeScript developers can take advantage of thenpmjstype declaration (typings) file repository to get IntelliSense for common JavaScript libraries (Node.js, React, Angular). You can find a good explanation on using type declaration files in theJavaScript languagetopic and theNode.jstutorial.

Learn more in theIntelliSense document.

Formatting

VS Code has great support for source code formatting. The editor has two explicit format actions:

  • Format Document(⇧⌥F(WindowsShift+Alt+F,LinuxCtrl+Shift+I)) - Format the entire active file.
  • Format Selection(⌘K ⌘F(Windows, LinuxCtrl+K Ctrl+F)) - Format the selected text.

You can invoke these from theCommand Palette(⇧⌘P(Windows, LinuxCtrl+Shift+P)) or the editor context menu.

VS Code has default formatters for JavaScript, TypeScript, JSON, HTML, and CSS. Each language has specific formatting options (for example,html.format.indentInnerHtml) which you can tune to your preference in your user or workspacesettings.You can also disable the default language formatter if you have another extension installed that provides formatting for the same language.

"html.format.enable":false

Along with manually invoking code formatting, you can also trigger formatting based on user gestures such as typing, saving or pasting. These are off by default but you can enable these behaviors through the followingsettings:

  • editor.formatOnType- Format the line after typing.
  • editor.formatOnSave- Format a file on save.
  • editor.formatOnPaste- Format the pasted content.

Note: Not all formatters support format on paste as to do so they must support formatting a selection or range of text.

In addition to the default formatters, you can find extensions on the Marketplace to support other languages or formatting tools. There is aFormatterscategory so you can easily search and findformatting extensions.In theExtensionsview search box, type 'formatters' or 'category:formatters' to see a filtered list of extensions within VS Code.

Folding

You can fold regions of source code using the folding icons on the gutter between line numbers and line start. Move the mouse over the gutter and click to fold and unfold regions. UseShift + Clickon the folding icon to fold or unfold the region and all regions inside.

Folding

You can also use the following actions:

  • Fold (⌥⌘[(Windows, LinuxCtrl+Shift+[)) folds the innermost uncollapsed region at the cursor.
  • Unfold (⌥⌘](Windows, LinuxCtrl+Shift+])) unfolds the collapsed region at the cursor.
  • Toggle Fold (⌘K ⌘L(Windows, LinuxCtrl+K Ctrl+L)) folds or unfolds the region at the cursor.
  • Fold Recursively (⌘K ⌘[(Windows, LinuxCtrl+K Ctrl+[)) folds the innermost uncollapsed region at the cursor and all regions inside that region.
  • Unfold Recursively (⌘K ⌘](Windows, LinuxCtrl+K Ctrl+])) unfolds the region at the cursor and all regions inside that region.
  • Fold All (⌘K ⌘0(Windows, LinuxCtrl+K Ctrl+0)) folds all regions in the editor.
  • Unfold All (⌘K ⌘J(Windows, LinuxCtrl+K Ctrl+J)) unfolds all regions in the editor.
  • Fold Level X (⌘K ⌘2(Windows, LinuxCtrl+K Ctrl+2)for level 2) folds all regions of level X, except the region at the current cursor position.
  • Fold All Block Comments (⌘K ⌘/(Windows, LinuxCtrl+K Ctrl+/)) folds all regions that start with a block comment token.

Folding regions are by default evaluated based on the indentation of lines. A folding region starts when a line has a smaller indent than one or more following lines, and ends when there is a line with the same or smaller indent.

Folding regions can also be computed based on syntax tokens of the editor's configured language. The following languages already provide syntax aware folding: Markdown, HTML, CSS, LESS, SCSS, and JSON.

If you prefer to switch back to indentation-based folding for one (or all) of the languages above, use:

"[html]":{
"editor.foldingStrategy":"indentation"
},

Regions can also be defined by markers defined by each language. The following languages currently have markers defined:

Language Start region End region
Bat ::#regionorREM #region ::#endregionorREM #endregion
C# #region #endregion
C/C++ #pragma region #pragma endregion
CSS/Less/SCSS /*#region*/ /*#endregion*/
Coffeescript #region #endregion
F# //#regionor(#_region) //#endregionor(#_endregion)
Java //#regionor//<editor-fold> //#endregionor//</editor-fold>
Markdown <!-- #region --> <!-- #endregion -->
Perl5 #regionor=pod #endregionor=cut
PHP #region #endregion
PowerShell #region #endregion
Python #regionor# region #endregionor# endregion
TypeScript/JavaScript //#region //#endregion
Visual Basic #Region #End Region

To fold and unfold only the regions defined by markers use:

  • Fold Marker Regions (⌘K ⌘8(Windows, LinuxCtrl+K Ctrl+8)) folds all marker regions.
  • Unfold Marker Regions (⌘K ⌘9(Windows, LinuxCtrl+K Ctrl+9)) unfolds all marker regions.

Fold selection

The commandCreate Manual Folding Ranges from Selection(⌘K ⌘,(Windows, LinuxCtrl+K Ctrl+,)) creates a folding range from the currently selected lines and collapses it. That range is called amanualfolding range that goes on top of the ranges computed by folding providers.

Manual folding ranges can be removed with the commandRemove Manual Folding Ranges(⌘K ⌘.(Windows, LinuxCtrl+K Ctrl+.)).

Manual folding ranges are especially useful for cases when there isn't programming language support for folding.

Indentation

VS Code lets you control text indentation and whether you'd like to use spaces or tab stops. By default, VS Code inserts spaces and uses 4 spaces perTabkey. If you'd like to use another default, you can modify theeditor.insertSpacesandeditor.tabSizesettings.

"editor.insertSpaces":true,
"editor.tabSize":4,

Auto-detection

VS Code analyzes your open file and determines the indentation used in the document. The auto-detected indentation overrides your default indentation settings. The detected setting is displayed on the right side of the Status Bar:

auto detect indentation

You can click on the Status Bar indentation display to bring up a dropdown with indentation commands allowing you to change the default settings for the open file or convert between tab stops and spaces.

indentation commands

Note:VS Code auto-detection checks for indentations of 2, 4, 6 or 8 spaces. If your file uses a different number of spaces, the indentation may not be correctly detected. For example, if your convention is to indent with 3 spaces, you may want to turn offeditor.detectIndentationand explicitly set the tab size to 3.

"editor.detectIndentation":false,
"editor.tabSize":3,

File encoding support

Set the file encoding globally or per workspace by using thefiles.encodingsetting inUser SettingsorWorkspace Settings.

files.encoding setting

You can view the file encoding in the status bar.

Encoding in status bar

Click on the encoding button in the status bar to reopen or save the active file with a different encoding.

Reopen or save with a different encoding

Then choose an encoding.

Select an encoding

Compare files

VS Code supports several ways to compare the content of the current file or of any two files.

When you have an active file open in the editor, you have the following compare options:

  • Compare with a workspace file:in the Command Palette, selectFile: Compare Active File With...,and then choose another file to compare with.
  • Compare with clipboard:in the Command Palette, selectFile: Compare Active File with Clipboard(⌘K C(Windows, LinuxCtrl+K C)) to compare the current file with the clipboard content.
  • Compare with saved:in the Command Palette, selectFile: Compare Active File with Saved(⌘K D(Windows, LinuxCtrl+K D)) to compare the current file with the last saved version.

To compare any two files:

  • Right-click on a file in the Explorer view and selectSelect for Compare.Then, right-click on a second file and selectCompare with Selected.
  • To start a comparison between two empty editor windows, selectFile: Compare New Untitled Text Filesfrom the Command Palette.

Tip:You can start VS Code from the command line with the--diffoption to compare two files. Learn more about theVS Code command line interface.

Next steps

You've covered the basic user interface - there is a lot more to VS Code. Read on to find out about:

Common questions

Is it possible to globally search and replace?

Yes, expand the Search view text box to include a replace text field. You can search and replace across all the files in your workspace. Note that if you did not open VS Code on a folder, the search will only run on the currently open files.

global search and replace

How do I turn on word wrap?

You can control word wrap through theeditor.wordWrapsetting.By default,editor.wordWrapisoffbut if you set to it toon,text will wrap on the editor's viewport width.

"editor.wordWrap":"on"

You can toggle word wrap for the VS Code session with⌥Z(Windows, LinuxAlt+Z).

You can also add vertical column rulers to the editor with theeditor.rulerssetting, which takes an array of column character positions where you'd like vertical rulers.

As in other editors, commands such asCutandCopyapply to the whole wrapped line. Triple-click selects the whole wrapped line. PressingHometwice moves the cursor to the very beginning of the line. PressingEndtwice moves the cursor to the very end of the line.

How can I avoid placing extra cursors in word wrapped lines?

If you'd like to ignore line wraps when adding cursors above or below your current selection, you can pass in{ "logicalLine": true }toargson the keybinding like this:

{
"key":"shift+alt+down",
"command":"editor.action.insertCursorBelow",
"when":"textInputFocus",
"args":{"logicalLine":true},
},
{
"key":"shift+alt+up",
"command":"editor.action.insertCursorAbove",
"when":"textInputFocus",
"args":{"logicalLine":true},
},