title | description | ms.date | ms.topic | f1_keywords | helpviewer_keywords | author | ms.author | manager | ms.technology | ms.workload | |||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Find and replace text, and multi-caret selection |
Learn about the Find and Replace feature and how to use it to find and replace instances of a pattern. |
01/12/2023 |
conceptual |
|
|
TerryGLee |
tglee |
jmartens |
vs-ide-general |
multiple |
Find and replace text
[!INCLUDE Visual Studio]
You can find and replace text in the Visual Studio editor by using Find and Replace (Ctrl+F or Ctrl+H) or Find/Replace in Files (Ctrl+Shift+F or Ctrl+Shift+H). You can also find and replace some instances of a pattern by using multi-caret selection.
[!NOTE]
The content on this page applies to Visual Studio. If you’re looking for information that’s specific to Visual Studio Code—also known as VS Code—see the Find and Replace section of the Basic Editing page in the Visual Studio Code docs.
[!TIP]
In Visual Studio, if you’re renaming code symbols such as variables and methods, it’s better to refactor them than to use find-and-replace. Refactoring is intelligent and understands scope, whereas find-and-replace blindly replaces all instances.
Find-and-replace functionality is available in the editor, in certain other text-based windows such as the Find Results windows, in designer windows such as the XAML designer and Windows Forms designer, and in tool windows.
You can scope searches to the current document, the current solution, or a custom set of folders. You can also specify a set of file name extensions for multi-file searches. Customize search syntax by using .NET regular expressions.
[!TIP]
The Find/Command box is available as a toolbar control, but isn’t visible by default. To display the Find/Command box, select Add or Remove Buttons on the Standard toolbar, and then select Find.
Find and Replace control
- Press Ctrl+F as a shortcut to find a string in the current file.
- Press Ctrl+H as a shortcut to find and replace a string in the current file.
The Find and Replace control appears in the upper right corner of the code editor window. It immediately highlights every occurrence of the given search string in the current document. You can navigate from one occurrence to another by choosing the Find Next button or the Find Previous button on the search control.
::: moniker range=»vs-2022″
:::image type=»content» source=»media/vs-2022/find-and-replace-box.png» alt-text=»Screenshot of the Find and Replace dialog in the Editor in Visual Studio 2022.»:::
::: moniker-end
::: moniker range=»<=vs-2019″
:::image type=»content» source=»media/find-and-replace-box.png» alt-text=»Screenshot of the Find and Replace dialog in the Editor in Visual Studio 2019 and earlier versions.»:::
::: moniker-end
You can access replacement options by choosing the button next to the Find text box. To make one replacement at a time, choose the Replace Next button next to the Replace text box. To replace all matches, choose the Replace All button.
To change the highlight color for matches, choose the Tools menu, select Options, and then choose Environment, and select Fonts and Colors. In the Show settings for list, select Text Editor, and then in the Display items list, select Find Match Highlight.
Search tool windows
You can use the Find control in code or text windows, such as Output windows and Find Results windows, by selecting Edit > Find and Replace or pressing Ctrl+F.
A version of the Find control is also available in some tool windows. For example, you can filter the list of controls in the Toolbox window by entering text in the search box. Other tool windows that allow you to search their contents include Solution Explorer, the Properties window, and Team Explorer.
Find in Files and Replace in Files
- Press Ctrl+Shift+F as a shortcut to find a string in multiple files.
- Press Ctrl+Shift+H as a shortcut to find and replace a string in multiple files.
Find/Replace in Files works like the Find and Replace control, except that you can define a scope for your search. Not only can you search the current open file in the editor, but also all open documents, the entire solution, the current project, and selected folder sets. You can also search by file name extension. To access the Find/Replace in Files dialog box, select Find and Replace on the Edit menu (or press Ctrl+Shift+F).
::: moniker range=»>=vs-2022″
:::image type=»content» source=»media/vs-2022/find-files.png» alt-text=»Screenshot of the Find and Replace dialog box in Visual Studio 20222, with the Find in Files tab open.»:::
For more detailed information, see the Find in Files and Replace in Files pages.
::: moniker-end
::: moniker range=»vs-2019″
:::image type=»content» source=»media/find-files-vs2019.png» alt-text=»Screenshot of the Find and Replace dialog box in Visual Studio 2019, with the Find in Files tab open.»:::
For more detailed information, see the Find in Files and Replace in Files pages.
[!IMPORTANT]
If you are using Visual Studio 2019 version 16.6 or earlier, the Find and Replace dialog box might not look like it appears here. Switch to the Visual Studio 2017 version of this page for descriptions that’ll match what you see on your screen.
::: moniker-end
Find Results
When you choose Find All, a Find Results window opens and lists the matches for your search. Selecting a result in the list displays the associated file and highlights the match. If the file is not already open for editing, it is opened in a preview tab in the right side of the tab well. You can use the Find control to search through the Find Results list.
Create custom search folder sets
You can define a search scope by choosing the Choose Search Folders button (it looks like …) next to the Look in box. In the Choose Search Folders dialog box, you can specify a set of folders to search, and you can save the specification so that you can reuse it later.
[!TIP]
If you’ve mapped a remote machine’s drive to your local machine, you can specify folders to search on the remote machine.
Create custom component sets
You can define component sets as your search scope by choosing the Edit Custom Component Set button next to the Look in box. You can specify installed .NET or COM components, Visual Studio projects that are included in your solution, or any assembly or type library (.dll, .tlb, .olb, .exe, or .ocx). To search references, select the Look in references box.
Multi-caret selection
[!NOTE]
This section applies to Visual Studio on Windows. For Visual Studio for Mac, see Block selection.
Use multi-caret selection to make the same edit in two or more places at the same time. For example, you can insert the same text or modify existing text in multiple locations at the same time.
::: moniker range=»vs-2022″
In Visual Studio 2022, we improved the multi-caret copy and paste experience. Previously, pasting multiple lines into multiple carets resulted in the entire clipboard being duplicated at each caret. Now, pasting multiple lines into the same number of carets will insert each line to a respective caret.
To use multi-caret, press Alt+Shift+mouse click or Alt+Shift+. and then use Ctrl+Shift+arrow key to expand selections. Next, press Ctrl+C to copy the text in multiple selections. Use Alt+Shift+mouse click to create multiple carets for each line to paste in where you want them. Finally, press Ctrl+V to paste each line at its own caret.
:::image type=»content» source=»media/vs-2022/multi-caret-copy-paste.gif» alt-text=»An animation of the multi-caret selection action in Visual Studio.»:::
Additionally, you can use Alt+Shift+up arrow key (or down arrow key) or Alt+Shift+mouse drag to select with multiple carets. Previously, these gestures created a box selection. Now, a box selection transforms into multiple carets. This method is easier and faster than having to click in precise locations to insert individual carets.
[!TIP]
If you prefer to keep using a box selection with Alt+Shift+arrow keys and Alt+Shift+mouse drag when you expand a multi-caret selection, go to Tools > Options > Text Editor > Advanced and select Use box selection.
Commands
The following keyboard shortcuts are for actions that are specific to multi-caret selection behaviors.
Shortcut | Action | Command |
---|---|---|
Alt+Shift+. | Use multi-caret | Edit.InsertNextMatchingCaret |
Ctrl+Shift+arrow key | Expand selections | Edit.SizeControlUp, Edit.SizeControlDown, Edit.SizeControlRight, Edit.SizeControlLeft |
Alt+Shift+up arrow key (or down arrow key) | Select multiple carets | Edit.LineUpExtendColumn, Edit.LineDownExtendColumn |
You can also access multi-caret selection from the menu bar by selecting Edit > Multiple Carets and then selecting the action you want.
:::image type=»content» source=»media/vs-2022/edit-menu-multiple-carets-find-replace.png» alt-text=»Screenshot of the Multiple Carets fly-out menu in Visual Studio 2022.»:::
::: moniker-end
::: moniker range=»<=vs-2019″
In the following screenshot, -0000
is selected in three locations; if the user presses Delete, all three selections are deleted:
To select multiple carets, click or make first text selection as usual, and then press Ctrl+Alt while you click or select text in each additional location. You can also automatically add matching text as additional selections, or select a box of text to edit identically on each line.
[!TIP]
If you’ve selected Alt as the modifier key for mouse-click in «Go to Definition» from Tools > Options > Text Editor > General, multi-caret select is disabled. For more information, see Options dialog box: Text Editor /> General.
Commands
Use the following keys and actions for multi-caret selection behaviors:
Shortcut | Action |
---|---|
Ctrl+Alt + click | Add a secondary caret |
Ctrl+Alt + double-click | Add a secondary word selection |
Ctrl+Alt + click + drag | Add a secondary selection |
Shift+Alt+. | Add the next matching text as a selection |
Shift+Alt+; | Add all matching text as selections |
Shift+Alt+, | Remove last selected occurrence |
Shift+Alt+/ | Skip next matching occurrence |
Alt + click | Add a box selection |
Esc or click | Clear all selections |
Some of the commands are also available on the Edit menu, under Multiple Carets:
:::image type=»content» source=»media/edit-menu-multiple-carets-find-replace.png» alt-text=»Screenshot of the Multiple Carets fly-out menu in Visual Studio»:::
::: moniker-end
See also
- Use regular expressions in Visual Studio
- Refactor code in Visual Studio
- Block selection (Visual Studio for Mac)
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.
- Keyboard Shortcuts Reference — Learn the most commonly used and popular keyboard shortcuts by downloading the reference sheet.
- Install a Keymap extension — Use the keyboard shortcuts of your old editor (such as Sublime Text, Atom, and Vim) in VS Code by installing a Keymap extension.
- Customize Keyboard Shortcuts — Change the default keyboard shortcuts to fit your style.
Multiple selections (multi-cursor)
VS Code supports multiple cursors for fast simultaneous edits. You can add secondary cursors (rendered thinner) with Alt+Click. Each cursor operates independently based on the context it sits in. A common way to add more cursors is with ⌥⌘↓ (Windows Ctrl+Alt+Down, Linux Shift+Alt+Down) or ⌥⌘↑ (Windows Ctrl+Alt+Up, Linux Shift+Alt+Up) that insert cursors below or above.
Note: Your graphics card driver (for example NVIDIA) might overwrite these default shortcuts.
⌘D (Windows, Linux Ctrl+D) selects the word at the cursor, or the next occurrence of the current selection.
Tip: You can also add more cursors with ⇧⌘L (Windows, Linux Ctrl+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 to Cmd+Click on macOS and Ctrl+Click on Windows and Linux, you can do so with the editor.multiCursorModifier
setting. 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 to Ctrl on Windows and Cmd on macOS.alt
— The existing default Alt.
There’s also a menu item Use Ctrl+Click for Multi-Cursor in the Selection menu to quickly toggle this setting.
The Go to Definition and Open Link gestures will also respect this setting and adapt such that they do not conflict. For example, when the setting is ctrlCmd
, multiple cursors can be added with Ctrl/Cmd+Click, and opening links or going to definition can be invoked with Alt+Click.
Shrink/expand selection
Quickly shrink or expand the current selection. Trigger it with ⌃⇧⌘← (Windows, Linux Shift+Alt+Left) and ⌃⇧⌘→ (Windows, Linux Shift+Alt+Right).
Here’s an example of expanding the selection with ⌃⇧⌘→ (Windows, Linux Shift+Alt+Right):
Column (box) selection
Place the cursor in one corner and then hold Shift+Alt while dragging to the opposite corner:
Note: This changes to Shift+Ctrl/Cmd when using Ctrl/Cmd as multi-cursor modifier.
There are also default key bindings for column selection on macOS and Windows, but not on Linux.
Key | Command | Command ID |
---|---|---|
⇧↓ (Windows Ctrl+Shift+Alt+Down, Linux ) | Column Select Down | cursorColumnSelectDown |
⇧↑ (Windows Ctrl+Shift+Alt+Up, Linux ) | Column Select Up | cursorColumnSelectUp |
⇧← (Windows Ctrl+Shift+Alt+Left, Linux ) | Column Select Left | cursorColumnSelectLeft |
⇧→ (Windows Ctrl+Shift+Alt+Right, Linux ) | Column Select Right | cursorColumnSelectRight |
⇧PageDown (Windows Ctrl+Shift+Alt+PageDown, Linux ) | Column Select Page Down | cursorColumnSelectPageDown |
⇧PageUp (Windows Ctrl+Shift+Alt+PageUp, Linux ) | Column Select Page Up | cursorColumnSelectPageUp |
You can edit your keybindings.json
to bind them to something more familiar if you want.
Column Selection mode
The user setting Editor: Column Selection controls 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 the Selection > Column Selection Mode menu 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, Linux Ctrl+S).
However, it’s easy to turn on Auto 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 on Auto Save
is with the File > Auto Save toggle that turns on and off save after a delay.
For more control over Auto Save
, open User or Workspace settings and 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.autoSave
is configured toafterDelay
. The default is 1000 ms.
Hot Exit
VS Code will remember unsaved changes to files when you exit by default. Hot exit is triggered when the application is closed via File > Exit (Code > Quit on macOS) or when the last window is closed.
You can configure hot exit by setting files.hotExit
to 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.quit
command is triggered (from the Command 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.quit
command is triggered (from the Command 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.restoreWindows
toall
.
If something happens to go wrong with hot exit, all backups are stored in the following folders for standard install locations:
- Windows
%APPDATA%CodeBackups
- 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, Linux Ctrl+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 press Enter and ⇧Enter (Windows, Linux Shift+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.
This feature can be turned off by setting editor.find.seedSearchStringFromSelection
to false
.
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.
If you want it to be the default behavior of the Find Widget, you can set editor.find.autoFindInSelection
to always
, or to multiline
, 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. Pressing Ctrl+Enter
inserts a new line in the input box.
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.
Search across files
VS Code allows you to quickly search over all files in the currently opened folder. Press ⇧⌘F (Windows, Linux Ctrl+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.
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, Linux Ctrl+Shift+J)). This will show additional fields to configure the search.
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 enter example
, that will match every folder and file named example
in the workspace. If you enter ./example
, that will match the folder example/
at the top level of your workspace. Use ,
to separate multiple patterns. Paths must use forward slashes. You can also use glob syntax:
*
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)[]
to declare a 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
). Open settings to change these rules under the files.exclude
and search.exclude
section.
Note that glob patterns in the search view work differently than in settings such as files.exclude
and search.exclude
. In the settings, you must use **/example
to match a folder named example
in subfolder folder1/example
in 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 the Use Exclude Settings and Ignore Files toggle button in the files to exclude box. The toggle determines whether to exclude files that are ignored by your .gitignore
files and/or matched by your files.exclude
and search.exclude
settings.
Tip: From the Explorer, you can right-click on a folder and select Find in Folder to 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.
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.
Tip: You can quickly reuse a previous search term by using ↓ (Windows, Linux Down) and ↑ (Windows, Linux Up) 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 uUlL
, where u
and l
will upper/lowercase a single character, and U
and L
will upper/lowercase the rest of the matching group.
Example:
The modifiers can also be stacked — for example, uuu$1
will uppercase the first three characters of the group, or lU$1
will lowercase the first character, and uppercase the rest. The capture group is referenced by $n
in the replacement string, where n
is 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:
The Open Search Editor command opens an existing Search Editor if one exists, or to otherwise create a new one. The New Search Editor command will always create a new Search Editor.
In the Search Editor, results can be navigated to using Go to Definition actions, such as F12 to open the source location in the current editor group, or ⌘K F12 (Windows, Linux Ctrl+K F12) to open the location in an editor to the side. Additionally, double-clicking can optionally open the source location, configurable with the search.searchEditor.doubleClickBehaviour
setting.
You can also use the Open New Search Editor button at the top of the Search view, and can copy your existing results from a Search view over to a Search Editor with the Open in editor link at the top of the results tree, or the Search Editor: Open Results in Editor command.
The Search Editor above was opened by selecting the Open New Search Editor button (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
The search.searchEditor.defaultNumberOfContextLines
setting 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
The search.searchEditor.reusePriorSearchConfiguration
setting (default is false
) 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 rich languages, 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, Linux Ctrl+Space). By default, Tab or Enter are the accept keyboard triggers but you can also customize 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 the
editor.quickSuggestions
andeditor.suggestOnTriggerCharacters
settings.
JavaScript and TypeScript developers can take advantage of the npmjs type 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 the JavaScript language topic and the Node.js tutorial.
Learn more in the IntelliSense document.
Formatting
VS Code has great support for source code formatting. The editor has two explicit format actions:
- Format Document (⇧⌥F (Windows Shift+Alt+F, Linux Ctrl+Shift+I)) — Format the entire active file.
- Format Selection (⌘K ⌘F (Windows, Linux Ctrl+K Ctrl+F)) — Format the selected text.
You can invoke these from the Command Palette (⇧⌘P (Windows, Linux Ctrl+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 workspace settings. 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 following settings:
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 a Formatters
category so you can easily search and find formatting extensions. In the Extensions view 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. Use Shift + Click on the folding icon to fold or unfold the region and all regions inside.
You can also use the following actions:
- Fold (⌥⌘[ (Windows, Linux Ctrl+Shift+[)) folds the innermost uncollapsed region at the cursor.
- Unfold (⌥⌘] (Windows, Linux Ctrl+Shift+])) unfolds the collapsed region at the cursor.
- Toggle Fold (⌘K ⌘L (Windows, Linux Ctrl+K Ctrl+L)) folds or unfolds the region at the cursor.
- Fold Recursively (⌘K ⌘[ (Windows, Linux Ctrl+K Ctrl+[)) folds the innermost uncollapsed region at the cursor and all regions inside that region.
- Unfold Recursively (⌘K ⌘] (Windows, Linux Ctrl+K Ctrl+])) unfolds the region at the cursor and all regions inside that region.
- Fold All (⌘K ⌘0 (Windows, Linux Ctrl+K Ctrl+0)) folds all regions in the editor.
- Unfold All (⌘K ⌘J (Windows, Linux Ctrl+K Ctrl+J)) unfolds all regions in the editor.
- Fold Level X (⌘K ⌘2 (Windows, Linux Ctrl+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, Linux Ctrl+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 | ::#region or REM #region |
::#endregion or REM #endregion |
C# | #region |
#endregion |
C/C++ | #pragma region |
#pragma endregion |
CSS/Less/SCSS | /*#region*/ |
/*#endregion*/ |
Coffeescript | #region |
#endregion |
F# | //#region or (#_region) |
//#endregion or (#_endregion) |
Java | //#region or //<editor-fold> |
// #endregion or //</editor-fold> |
Markdown | <!-- #region --> |
<!-- #endregion --> |
Perl5 | #region or =pod |
#endregion or =cut |
PHP | #region |
#endregion |
PowerShell | #region |
#endregion |
Python | #region or # region |
#endregion or # 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, Linux Ctrl+K Ctrl+8)) folds all marker regions.
- Unfold Marker Regions (⌘K ⌘9 (Windows, Linux Ctrl+K Ctrl+9)) unfolds all marker regions.
Fold selection
The command Create Manual Folding Ranges from Selection (⌘K ⌘, (Windows, Linux Ctrl+K Ctrl+,)) creates a folding range from the currently selected lines and collapses it. That range is called a manual folding range that goes on top of the ranges computed by folding providers.
Manual folding ranges can be removed with the command Remove Manual Folding Ranges (⌘K ⌘. (Windows, Linux Ctrl+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 per Tab key. If you’d like to use another default, you can modify the editor.insertSpaces
and editor.tabSize
settings.
"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:
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.
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 off
editor.detectIndentation
and 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 the files.encoding
setting in User Settings or Workspace Settings.
You can view the file encoding in the status bar.
Click on the encoding button in the status bar to reopen or save the active file with a different encoding.
Then choose an encoding.
Next steps
You’ve covered the basic user interface — there is a lot more to VS Code. Read on to find out about:
- Intro Video — Setup and Basics — Watch a tutorial on the basics of VS Code.
- User/Workspace Settings — Learn how to configure VS Code to your preferences through user and workspace settings.
- Code Navigation — Peek and Goto Definition, and more.
- Integrated Terminal — Learn about the integrated terminal for quickly performing command-line tasks from within VS Code.
- IntelliSense — VS Code brings smart code completions.
- Debugging — This is where VS Code really shines.
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.
How do I turn on word wrap?
You can control word wrap through the editor.wordWrap
setting. By default, editor.wordWrap
is off
but if you set to it to on
, 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, Linux Alt+Z).
You can also 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.
If you’d like to ignore line wraps when adding cursors above or below your current selection, you can pass in { "logicalLine": true }
to args
on 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 },
},
5/3/2023
Сюда буду добавлять горячие клавиши в Visual Studio, способы быстрого ввода и прочие фишки, позволяющие кодить более комфортно.
Начнем с самого простого, что бывает нужно начинающему программисту:
cw + 2 раза Tab = Console.WriteLine();
Далее материалы статьи с Хабра, где-то с моими дополнениями, но в основном в чистом виде:
===============================================
Комментирование
Ctrl+K,C — закомментировать выбранные линии в коде.
Ctrl+K,U — раскомментировать выбранные линии в коде.
Если перед именем метода набрать /// — автоматически будут добавлены XML комментарии, которые потом можно использовать для создания документации. Туда можно вписать название метода, описание переменных и т.п. Далее при использовании данного метода будут всплывать подсказки как раз с этой информацией.
Поиск
Ctrl+F — открывается стандартное окно поиска, если в буфер недавно было скопирован текст, то он автоматически подставиться.
Ctrl+F3 — поиск «активного» текста вниз (который выделен или слово на котором стоит курсор), без копирования в буфер обмена.
Ctrl+Shift+F3 — поиск «активного» текста вверх.
Ctrl+I — и начинаете печатать текст, этакий runtime поиск.
Вызов базового джина
Вам лень писать текст полностью?! Скорость выпадающего Intellisence не устраивает несущуюся впереди вас вашу мысль?!
Тогда самое время применить следующии комбинации:
Ctrl+Space — вызов Intellisence с показом «слов»
Ctrl+J — если вы подзабыли название метода класса или его свойсто, то эта комбинация вам поможет. Можно применять и предыдущую, но эта более «умная».
Ctrl+K, X — показ всех сниппетов, которые у вас есть, в виде выпадающего списка, использование интуитивно понятно 🙂
короткое_имя_снипета+Tab — использовать сниппет в коде.
Навигация по коду
Тут стоит сказать отдельно и довольно много, навигация очень удобная, особенно когда привыкаешь 🙂
F12 — перейти к определению/объявлению класса/метода/свойства. Очень применимо если вам вдруг стало интересно, а реализуется ли этой переменной, этого класса тип интерфейс IDisposable; или вы ищите в коде, «а где же объявляется эта переменная».
Ctrl+G — перейти на определённый номер строки в коде. (Отображение номеров строк можно включить: Text Editor -> Интересующий вас язык -> Display -> Line numbers — выставить галку). Иногда довольно удобно, особенно если получаете описание необработанного исключения, а там указан, как правило, номер строки.
Ctrl+] — когда курсор установлен на скобку, многострочный комментарий (/* */), регион (#region), строку, обрамлённую кавычками, эта комбинация позволит вам увидеть начало и окончание этих «блоков», перемещая курсор между ними.
Ctrl+M, M — я человек довольно ленивый и мне сложно заставить долго тыкать мышкой по ±, сворачиваю и разворачия «блоки», поэтому рекомендую данную комбинацию
Ctr+M, O — комбинация аналогичная предыдущей, только сворачивает все блоки
Ctrl+- — переход к предыдущему активному тексту (тому который вы редактировали)
Ctrl+Shift+- — переход к следующему активному тексту, если он конечно есть 😉
Если обратите внимание то студия, по своей природе MDI, значит должна быть возможность перемещаться, между окнами:
Ctrl+Tab — аналог Alt+Tab в Windows, только применимо к студии.
Очень удобным инструментом в студии являются закладки, да-да, по аналогии с книжными. Можно отметить код чтобы потом перейти к нему:
Ctrl+B, T — поставить/снять закладку.
Ctrl+B, Ctrl+C — удалить все закладки.
Ctrl+B, N — перейти к следующей закладке.
Ctrl+B, P — перейти к предыдущей закладке.
Форматирование и редактирование
Многие знают и используют Ctrl+C и Ctrl+V, но студия обладает ещё рядом удобным комбинаций:
Ctrl+Shift+V — не отпуская Ctrl+Shift и нажимая на V, вы сможете вставить один из 10 последних кусков текста, скопированных в буфер обмена.
Tab — увеличить отступ.
Shift+Tab — уменьшить отступ.
Мне иногда не хватало вертикального выделения текста, бывает полезно. Оказывается и такая возможность есть! Стоит нажать Alt, и не отпуская, выделять мышкой текст. Но есть минус — меню и стрелочки клавиатуры :). Это решаемо, нажимаете Shift+Alt и используете стрелочки Left или Right
Если код доставшийся вам «грязен», не только по структуре, но и по внешнему оформлению, используйте:
Ctrl+E+D — форматирование всего документа, позволяет привести документ в более удобоваримый вид.
Ctrl+E+F — форматирование выбранной части текста
Иногда в целях рефакторинга или ещё каких-то благих начинаниях, есть смысл перевести все буквы в верхний или нижний регистр:
Ctrl+Shift+U — перевести выделенный блок в верхний регистр
Ctrl+U — перевести выделенный блок в нижний регистр
Небольшой экскурс в сборку и отладку
Конечно же со стороны хоткеев 🙂
Начнём со «сборки»:
Ctrl+Shift+B или F6 — собрать solution.
Shift+F6 — собрать активный проект.
Если честно, тут я немного пошаманил, заточив под себя, иногда бывает удобно пересобрать проект RebuildSolution, но почему-то хоткей для этого не предусмотрен, я поступил следующий образом:
F6 — собрать solution
Ctrl+Shift+B — пересобрать solution
Поступил я так из-за соображения, что иногда студия не выполняет пересборку проекта, а пишет «up-to-date», а мне нужно именно пересобрать.
Если появились ошибки, это плохо, но никто от них не застрахован:
F5 — запустить программу, с возможностью отладки. Или продолжить выполнение программы, после точки останова.
Ctrl+F5 — запустить программу без отладки
F9 — поставить/убрать точку останова — breakpoint
Ctrl+Shift+F9 — удалить все точки останова.
F10 — выполнить код, без захода внутрь
F11 — выполнить код, с заходом внутрь
В режиме отладки есть два типа просмотра — Watch и QuickWatch.
Вызвать QuickWatch вы можете нажав Ctrl+D, Q. Просто Watch — Ctrl+D, W.
===========================================
Полный список горячих клавиш есть здесь: https://msdn.microsoft.com/ru-ru/library/da5kh0wa.aspx
Моя работа здесь: Сарафан: поиск мастеров
VS Code Default Actions
# | Command | Shortcut | Command ID |
---|---|---|---|
1. | View: Show Explorer | CTRL+SHIFT+E | workbench.view.explorer |
2. | Focus current directory | ← (Left arrow) | |
3. | Right-click / Find in Folder… | ALT+SHIFT+F | filesExplorer.findInFolder |
Suggestion
The default commands are too slow, even when using keyboard shortcuts (it takes seven key presses).
First, let’s get rid of the left arrow press. By default, the filesExplorer.findInFolder
command requires a folder to be focused. However, it works perfectly with a file — by searching its parent folder.
- Preferences: Open Keyboard Shortcuts (CTRL+K, CTRL+S)
- Search for the
filesExplorer.findInFolder
command. - Right-click / Change When Expression (CTRL+K, CTRL+E)
- Remove the
explorerResourceIsFolder
requirement from When Expression. The result should be:explorerViewletVisible && filesExplorerFocus && !inputFocus
Now, the Find in Folder command works on files too, so the shortcut combo is down by one key. The next is ALT+SHIFT+F, which is annoying for two reasons:
- You have to remember when to press CTRL but when ALT, and it is easy to mess up.
- Some extensions use ALT+SHIFT+F for code auto-formatting — and I doubt that this a side effect you wish.
That’s why I suggest changing the shortcut to CTRL+SHIFT+F with some When Expression magic:
- Preferences: Open Keyboard Shortcuts (CTRL+K, CTRL+S)
- Search for
workbench.action.findInFiles
and set its When Expression to!filesExplorerFocus
- Search again for
filesExplorer.findInFolder
and change its keybinding to CTRL+SHIFT+F
Result
- CTRL+SHIFT+F triggers «Find in Folder» when File Explorer is focused, and the default «Find in Files» elsewhere.
- You have to press either CTRL+SHIFT+F to «Find in Files», or CTRL+SHIFT+E, CTRL+SHIFT+F to «Find in Folder». Easy to remember. Moreover, the latter can be optimized by keeping CTRL+SHIFT pressed while pressing E, then F
User Config
{
"key": "ctrl+shift+f",
"command": "workbench.action.findInFiles",
"when": "!filesExplorerFocus"
},
{
"key": "ctrl+shift+f",
"command": "filesExplorer.findInFolder",
"when": "explorerViewletVisible && filesExplorerFocus && !inputFocus"
}
Warning
The filesExplorer.findInFolder
command overwrites the «files to include» field. For example, you could have a file search pattern *.c,*.cpp,*.h,*.hpp
, which is now overwritten by the folder path. But you can always press ↑ (UpArrow) in the field to cycle through the history and restore the previous pattern.
#База знаний
- 3 фев 2021
-
11
Становимся многорукими волшебниками: ускоряемся с помощью хоткеев и парочки других приёмов.
vlada_maestro / shutterstock
В IT пришёл из наружной рекламы, где проработал с десяток лет. В Skillbox изучает веб-вёрстку. Увлекается археологией, диджеингом и плёночной фотографией.
Здорово экономят время разработчика горячие клавиши. Есть такие и в Visual Studio Code. Здесь даже можно создавать свои сочетания, но большинству пользователей хватает исходных комбинаций (особенно новичкам, у кого и так глаза разбегаются от уймы настроек).
Пройдёмся по самым полезным для начинающего верстальщика. Читайте и сразу же пробуйте.
Типичная задача
Найти все элементы с классом link и стилизовать некоторые, присвоив им дополнительный класс.
Что делать
Нажмите Ctrl + F (Windows) или ⌘Cmd + F (macOS). Введите искомое — высветятся все найденные места. Остаётся перемещаться по ним (стрелочками в форме поиска).
Ситуация
Вы хотите создать комментарий или временно отключить участок кода (например, чтобы проверить работу оставшейся части).
Что делать
Выделите нужный участок и нажмите Ctrl + / (Windows) или ⌘Cmd + / (macOS). Если выделения нет, то закомментируется строка, в которой стоит курсор (раскомментировать её можно так же).
Типичные ситуации
- При проверке вёрстки понадобилось найти и изменить определённое свойство: инспектор кода в браузере показывает путь к нужному файлу (чаще всего со стилями) и номер строки в нём.
- В редакторе кода появляется сообщение об ошибке в определённой строке.
Что делать
Нажмите Ctrl + G (Windows) или ⌃Ctrl + G (macOS), введите номер строки — и вам не придётся листать вручную.
Типичная ситуация
Нужно изменить вложенность элемента, дать ему правильную обёртку. Вообще, перемещать элементы на уровень выше или ниже приходится часто, особенно на первых этапах вёрстки.
Что делать
Поставьте курсор на нужную строку и нажмите Alt + ↑ / ↓ (Windows) или
⌥Option + ↑ / ↓ (macOS).
Следите за сохранением структуры документа — не забывайте переносить и закрывающие теги.
Ситуация
В разметку надо быстро добавить одинаковые элементы. То есть вставить дубликат строки выше или ниже этой же строки.
Что делать
Поставьте курсор на нужную строку и нажмите Shift+Alt + ↓ / ↑ (Windows) или ⇧Shift + ⌥Option + ↓ / ↑ (macOS).
Типичная потребность
Быстро выровнять код, чтобы он стал более читаемым, понятным, красивым и соответствовал вашему код-стайлу (например, о джавишном читайте здесь).
Что делать
Жмите Shift + Alt + F (Windows) или ⇧Shift + ⌥Option + F (macOS).
Чтобы форматирование работало:
- Установите плагин форматирования кода.
- Настройте редактор в соответствии с вашим код-стайлом. И не забудьте выставить верное число отступов (общеприняты 2 или 4).
Мультикурсорность зрелищна сама по себе и здорово ускоряет работу верстальщика.
Ситуация
Вам понадобилось написать одно и то же сразу в нескольких местах.
Чтобы размножить курсор:
- Зажмите Alt (в Windows) или ⌥Option (в macOS) и кликайте левой кнопкой мышки там, куда нужно добавить курсор.
- Выделите несколько строк, зажав среднюю кнопку мыши. В каждой из выделенных строк появится по курсору.
- Если лень кликать мышкой, то дублировать курсор можно так: Ctrl + Alt + ↑ / ↓ (Windows) или ⌥Option + ⌘Cmd + ↑ / ↓ (macOS).
Ситуация
Нужно изменить одинаковый код сразу в нескольких местах.
Что делать
Выделите мышью символы и нажмите Ctrl + D (Windows) или ⌘Cmd + D (macOS). Если нажать больше одного раза, то к выделению добавится ещё одно вхождение того же куска далее по тексту. Затем можно редактировать все выделенные области сразу (подсвечиваются синим).
Как это работает
Вы набираете один-два символа, а автоподстановка предлагает название тега (в паре с закрывающим) для HTML или название свойства для CSS. Дождитесь, пока редактор подсветит предлагаемый вариант (когда их несколько — выберите нужный), и нажмите Tab или Enter.
Все доступные сокращения здесь. По мере запоминания ваши навыки и скорость будут расти, и, поверьте, это немалое удовольствие.
Зачем нужно
Чтобы быстрее создавать структуры из вложенных друг в друга тегов.
Например: нужно создать ненумерованный список, вложить в него четыре элемента, внутри каждого из которых будет по ссылке класса link. И всё это быстро-быстро.
Что делать
Достаточно набрать ul>li*4>a.link, дождаться подсветки этого варианта (он в выпадашке один) и нажать Tab или Enter, а редактор сам вставит развёрнутую конструкцию. Это очень ускоряет работу, хотя поначалу и похоже на волшебство.
Сложно представить реальную работу в VS Code без терминала.
Ситуация
Нужно вызвать терминал, с которым легче искать ошибки в коде (оповещения будут во вкладке Problems), а также работать с Git (распределённая система управления версиями).
Что делать
Нажать Ctrl + ` для Windows или ⌃Ctrl + ` для macOS.
Запоминать горячие клавиши вовсе не сложно, главное — начать их применять. Полные списки сочетаний тут и тут, а сокращений — здесь.
Желаем вам быстрой и приятной работы в VS Code!
Научитесь: Веб-вёрстка
Узнать больше