Auto-saving files upon changes with Visual Studio Code
I have used WebStorm from JetBrains for almost four years now. It’s a fantastic IDE for many reasons, but one of the best features is that it saves versions of files outside of version control. So if you accidentally delete files or lose files before they are saved by your version control system, WebStorm has a copy of them and there are visual diff tools to use. This feature has saved me on more than one occasion.
For Visual Studio Code, is there some feature/plugin that will auto-save copies of files as they change? Will Visual Studio Code save the files to some central location, or perhaps in the .vscode folder in the local workspace?
The feature in WebStorm is available from Local History → Show History from a folder or file. Here is an article about it: Using Local History for code changes tracking
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.
-
— Learn the most commonly used and popular keyboard shortcuts by downloading the reference sheet. — Use the keyboard shortcuts of your old editor (such as Sublime Text, Atom, and Vim) in VS Code by installing a Keymap extension. — 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.
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 the workbench.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 the workbench.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, set window.restoreWindows to all .
If something happens to go 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, 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 on example.0 , example.1 , …)
- [. ] to negate a range of characters to match ( example.[!0-9] to match on example.a , example.b , but not example.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 \u\U\l\L , where \u and \l will upper/lowercase a single character, and \U and \L will upper/lowercase the rest of the matching group.
The modifiers can also be stacked — for example, \u\u\u$1 will uppercase the first three characters of the group, or \l\U$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.
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 and editor.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.
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.
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:
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.
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.
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:
-
— Watch a tutorial on the basics of VS Code. — Learn how to configure VS Code to your preferences through user and workspace settings. — Peek and Goto Definition, and more. — Learn about the integrated terminal for quickly performing command-line tasks from within VS Code. — VS Code brings smart code completions. — 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.
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.
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 >to args on the keybinding like this:
Enable Auto Save in Visual Studio Code
When coding we mostly forget to save our programs and directly run them in visual studio code, and this sometimes leads to program being not compiled or executed, as we have to save the program before pressing the run button. Th ough there is a solution for this and in today’s article we’ll find out how to Enable AutoSave in Visual Studio Code.
Well, programming in visual studio code is a pretty enjoyable task but the only problem that occurs in visual studio code is off saving the written programs.
Video Tutorial: Enable Autosave in Visual Studio Code
Step 1: Enable Autosave in Visual Studio Code
1) Firstly open your visual studio code, and open settings by pressing “ Ctrl+, ” if you’re using a windows machine or press “ Cmd+, ” if you’re on a Mac machine.

2) Now in the search bar type “ autosave ” and in the “ Files: AutoSave ” list select the option “ afterdelay “.

3) After that in the “ Files: Auto Save Delay ” list, set your desired delay time in milliseconds after which visual studio code will automatically save the changes in a file. In our case, it’s “1000” .

And you’re all done , now visual studio code will automatically save the changes for you. Now you’re able to successfully enable autosave in visual studio code.
For more information about AutoSave feature in visual studio code, follow this Basic Editing in Visual Studio Code article from Microsoft.
Настройка Visual Studio Code для верстальщика: установка, добавление плагинов, отладка
Visual Studio Code — это мощный инструмент для верстальщика и программиста, который распространяется полностью бесплатно. Разработан Майкрософт на основе другого их продукта MS Visual Studio, который является более “громоздким” решением для профессионального программирования. Несмотря на то, что Visual Studio Code позиционируется как “облегченный” редактор кода, у него много настроек и плагинов от сторонних авторов, с помощью которых его можно превратить в профессиональный инструмент для верстальщика.
Первое знакомство с Visual Studio Code
Для начала рассмотрим, как скачать, установить, запустить (даже на очень слабом компьютере) и настроить Visual Studio Code. Вообще с этим проблем не должно возникнуть, так как на Windows все делается на интуитивно понятном уровне. Если у вас уже установлен этот редактор кода и в него внесены какие-то настройки, то лучше выполнить его полное удаление и, после чистой установки, настроить его заново.
Удаление VS Code ничем не отличается от удаление обычной программы. В Windows это можно сделать через “Панель управления”. Однако, чтобы наверняка убрать из памяти компьютера все настройки и ранее добавленные плагины рекомендуется провести очистку папки .vscode, которая расположена по адресу: C:\Пользователи\Ваше_имя_пользователя. Также очистите папку Code, что расположена в каталоге Roaming в AppData.
Скачивание и установка VS Code
Здесь нет ничего сложного — установочные материалы загружаются с официального сайта разработчика и проводится стандартная инсталляция:
1. Перейдя на главную страницу сайта разработчика воспользуйтесь кнопкой “Download”. По умолчанию сайт должен определить вашу ОС, но если он этого не сделал, то выберите ее самостоятельно в контекстном меню кнопки загрузки.

Скачивание VS Code
2. Ожидайте скачивание исполняемого файла. Запустите его, чтобы начать процесс установки.
3. Подтвердите, что вы ознакомились и согласны с лицензией для продолжения установки. Также в процессе инсталляции принимайте и добавляйте все, что вам предлагает мастер установки.
Первый запуск и возможные проблемы
С запуском VS Code не должно возникнуть проблем на большинстве современных машин. Исключениями могут является старые компьютеры или модели со слабыми процессорами. На них запуск редактора кода может либо занимать слишком много времени, либо выдавать просто черное окно, плюс, возможно появление проблем непосредственно в процессе работы. Еще сильнее “облегчить” Visual Studio Code можно с помощью изменения свойств ярлыка программы:
1. Кликните правой кнопкой мыши по ярлыку и откройте “Свойства” в контекстном меню.
2. В поле “Объект”, в самом конце пути пропишите флаг: —disable-gpu.
После этого VS Code должен без проблем запускаться и работать даже на очень слабых машинах.
Программа по умолчанию на английском языке и изменить это в настройках нельзя. Если вам удобнее работать с русским интерфейсом, то можно установить соответствующее расширение:
1. Переключитесь во вкладку плагинов. В поисковой строке введите “Russian Language Pack for Visual Studio Code”.
2. В результатах выдачи сразу покажут страницу этого плагина. Нажмите кнопку “Install”. После этого программа попросит перезапустить ее и откроется уже с русифицированным интерфейсом.

Установка русского языка для VS Code
Интерфейс Visual Studio Code
Интерфейс у редактора кода достаточно простой для освоения, однако некоторые детали требуют дополнительного рассмотрения и пояснений. Особенно это актуально для тех, кто только начинает изучать верстку и пока не знаком с некоторыми базовыми рабочими элементами редакторов кода.
Строка состояния
В самой нижней части интерфейса окна программы находится строка состояния. Там показывается количество ошибок и предупреждений, которые возникли в ходе выполнения кода. Также в этой области может выводится информация о состоянии тех или иных плагинов. Для получения подробной информации о предупреждениях и ошибках воспользуйтесь сочетанием клавиш Ctrl+Shift+M.
Вкладка “Вывод”
В этой вкладке отображается информация о работе всех программ и систем редактора. Ее можно отфильтровать по категориям с помощью переключателя в верхней части.
Вкладка “Терминал”
Здесь находится что-то вроде встроенной “Командной строки”. С помощью переключателя в верхнем части можно менять оболочки терминала. Также терминал можно условно разделить на несколько, например, с разными оболочками.

Терминал VS Code
Панель действий
Левая панель, на которой расположены основные элементы интерфейса, с которым разработчику придется взаимодействовать чаще всего:
1. Встроенный файловый менеджер. Здесь отображается файловая структура выбранного проекта с папками и файлами. С его помощью удобно вызывать нужный файл для редактирования. Также во встроенном проводнике можно создавать новые файлы и директории проекта.

Файловый менеджер VS Code
2. Поиск. Позволяет находить определенный фрагмент кода в открытых файлах проекта.

Поисковая строка VS Code
3. Центр управления и контроля версий. Позволяет осуществлять контроль версий проекта, например, с помощью Git.

Центр контроля версий VS Code
4. Запуск и отладка приложений. С помощью этого инструмента можно запускать выполнение кода и смотреть на его поведение. Функциональность можно расширить за счет дополнительных плагинов.

5. Расширения. Отсюда можно выполнить установку новых плагинов для VS Code, а также просмотреть список уже установленных.

Менеджер расширений VS Code
6. Настройки аккаунта. Вы можете авторизоваться в своем профиле, чтобы применить уже установленные ранее настройки для VS Code.
7. Настройки. Здесь представлены основные настройки, которые может менять пользователь. Их тут много и без сторонних плагинов.
Настройка основных параметров
Visual Studio Code позволяет выполнить настройку параметров как для всей программы в целом, так и задать их индивидуально для какого-то проекта. Для получения доступа к параметрам кликните по иконке шестеренки и выберите в контекстном меню “Settings”.

Переход в параметры VS Code
Далее подробно рассмотрим, что пользователь может настроить.
Автосохранение
По умолчанию возможность автоматического сохранения отключена, но ее рекомендуется включить. Это поможет не потерять важные данные из-за вылета редактора, а также избавит от необходимости делать сохранение вручную для отображения результата верстки или работы написанного скрипта.
Настройка автосохранения производится следующим образом:
1. При переходе в параметры VS Code должна автоматически открыться нужная вкладка, но если вы ее случайно сбили, то переключайтесь в “Commonly Used”.
2. В блоке “Files: Auto Save” по умолчанию стоит значение “Off”. Его нужно изменить на:
- afterDelay. Файл сохраняется раз в промежуток времени, настроенный пользователем;
- onfocusChange. Сохранение файла производится, когда вы переходите в другой файл проекта;
- onWindowChange. Сохранение производится при переключении на другое окно.

Автосохранение в VS Code
3. Выберите для себя удобный вариант автосохранения.
Настройка отображения кода
Для удобного редактирования кода настройте его отображение: размер и семейство шрифта, отступы, табуляцию. Рассмотрим настройку этих параметров:
1. Font Size. Здесь по умолчанию стоит 14 размер, но его можно изменить на любой произвольный.
2. Font Family. В это поле вручную прописывается название шрифта по умолчанию и его тип.
3. Tab Size. Настраивается шаг табуляции в пробелах. По умолчанию стоит значение 4. Его можно заменить на любое произвольное.
4. Render Whitespace. Управляет отрисовкой пробелов в редакторе. Доступно 5 вариантов:
- none — нет никакой дополнительной отрисовки;
- boundary — отрисовываются все пробелы, кроме одиночных между слов;
- selection — пробелы отрисовываются только в выделенном тексте (этот параметр выбран по умолчанию);
- trailing — отрисовываются конечные пробелы;
- all — отрисовываются все пробелы.
5. Cursor Style. Здесь можно выбрать стиль курсора. Всего доступно 6 стилей.
6. Insert Space. Отвечает за действие редактора при нажатии на клавишу Tab. По умолчанию здесь будут вставляться пробелы. Если снять галочку, то редактор будет вставлять знаки табуляции.
7. Word Wrap. Отвечает за автоматический перенос строк. По умолчанию он отключен, но можно сделать авто перенос по размеру окна и по пользовательским настройкам.

Настройки отображения в VS Code
Настройка подсказок
По умолчанию в VS Code включены некоторые подсказки при написании кода. Вы можете включите дополнительные подсказки или отключить уже имеющиеся. За это отвечает параметр “Hover Enabled”. Воспользуйтесь поисковой строкой по настройкам для быстрого перемещения к нему. По умолчанию данный параметр активен. Вы можете снять с него галочку и тогда большинство подсказок, появляющихся при наведении курсора на кусок кода, пропадут.
Однако помимо подсказок в таком случае пропадают и некоторые функции, которые могут быть полезны для работы со стилями. Например, подсветка цветов, написанных в виде RGB, HEX, RGBA. Помимо отображения самого цвета появится всплывающее окошко с палитрой, где можно быстро выбрать другой цвет и уровень прозрачности (при переключении на RGBA).
Если вам не нужно, чтобы в CSS не появлялись цветовые обозначения HEX/RGBA-палитры, то снимите галочку с параметра “Color Decorators”. В таком случае не будет вообще никаких подсказок, касательно цвета.
“Close Active Groups” — еще один параметр, на который рекомендуется обратить внимание. Отвечает за то, будет ли закрываться группа при закрытии последней вкладки в ней. Иногда автоматическое закрытие групп не очень удобно в работе, поэтому галочку с этого параметра можно снять.

Подсказки цветов в VS Code
Начинающим верстальщикам рекомендуется не отключать подсказки. Исключением могут быть параметры “Hover Enabled” и “Close Active Groups”, так как они действительно иногда могут мешать.
Настройка форматирования
В Visual Studio Code есть несколько параметров, отвечающих за форматирование кода. С помощью него можно, например, быстро исправить съехавшую табуляцию в документе. По умолчанию для этого используется сочетание клавиш Shift+Alt+F. Также есть возможность выбрать параметры для автоматического форматирования кода в файлах:
- Format On Paste — автоматическое форматирование при вставке кода, например, из буфера обмена;
- Format On Save — автоматическое форматирование в момент сохранения файла;
- Format On Type — форматирование производится автоматически в процессе печати.

Настройки форматирования в VS Code
В настройках можно сделать активным как один из рассмотренных параметров, так и несколько. По умолчанию они все неактивны. Автоматическая табуляция может быть полезна в том случае, если вам нужно получить читаемый и структурированный код, однако тратить время на самостоятельную постановку табов и пробелов не хочется. Однако в некоторых случаях автоматическое форматирование может наоборот мешать или срабатывать некорректно.
Настройка области написания кода
Ее настройку стоит рассмотреть отдельно. Здесь можно настроить несколько рабочих областей, разделив область написания кода на несколько частей. Это удобно в тех случаях, когда часто приходится взаимодействовать одновременно с несколькими файлами. Например, это актуально при верстке, когда разработчик пишет HTML-каркас и одновременно CSS-стили для него и JS-скрипты в отдельных файлах. Разделение на несколько рабочих областей можно сделать через меню “Вид”. Там выберите пункт “Макет редактора” и наиболее удобную для вас сетку.
Дополнительно в меню “Вид” доступна настройка масштабирования. Можно быстро увеличить или уменьшить шрифт в данном документе или проекте. Нужные настройки находятся в пункте “Внешний вид”. Там также можно вообще сбросить все настройки для всего документа. Также здесь можно скрывать или показывать разные элементы.
Режимы экрана
Предусмотрено несколько режимов работы с кодом:
1. Полноэкранный режим. Включается при нажатии клавиши F11. Скрывает верхнее меню и кнопки управления программой, а также панель задач Windows. Отключить этот режим можно повторным нажатием по клавише F11.

Полноэкранный режим в VS Code
2. Режим Zen. Почти тоже самое, что и полноэкранный режим, но он скрывает все элементы управления VS Code, позволяя сфокусироваться только на коде. Включить этот режим можно через меню “Вид”, выбрав раздел “Внешний вид” и затем “Режим Zen”.

Режим Zen в VS Code
Перенос текста
Иногда при вставке большого куска текста (просто текста, не кода) он может вставиться в виде длинной строки. Тогда появляется горизонтальная прокрутка, что не очень удобно. Этого можно избежать, воспользовавшись сочетанием клавиш Alt+Z. Текст после этого перестроится так, чтобы нормально помещаться в область работы с кодом без необходимости дополнительной прокрутки снизу.
Важные плагины VS Code для верстальщика
Главным преимуществом Visual Studio Code является возможность расширить имеющийся функционал за счет добавления плагинов и расширений. В начале статьи мы уже рассматривали процесс их установки на примере добавления расширения с русским языком. Всего доступно более 2 тысяч разных расширений и их список постоянно пополняется. Мы рекомендуем установить всего несколько штук, которые необходимы любому верстальщику.
Emmet
Данное расширение позволяет сокращать написание кода, использовать формулы для автоматического раскрытия больших структур кода. Например, поставив просто символ “!” в начале HTML-документа можно сразу же раскрыть его готовую начальную структуру со всеми необходимыми тегами. Также можно работать с элементами, например, если нужен div с классом block, то достаточно просто прописать .block и нужный div будет создан.
А вот пример использования формул. Предположим, вам требуется создать маркированный список на 10 элементов. Просто пропишите ul>li*10 и нажмите Tab. Список готов!
Emmet уже установлен в VS Code по умолчанию, однако мы рекомендуем изучить несколько дополнений к нему, которые есть в меню с расширениями. Некоторые из них могут вам сильно пригодиться.
Live Sass Compiler
Плагин отвечает за автоматическую компиляцию SASS/SCSS в обычный CSS. Рекомендуется к установке тем, кто работает с этими препроцессорами. Также компилятор позволяет импортировать содержимое других SASS/SCSS-файлов в основной. О корректной работе данного плагина будет говорить надпись Watch Sass в нижней части окна программы. При нажатии на нее открываются настройки плагина.

LiveSASS в VS Code
Live Server
Полезный плагин, который создает локальный сервер и позволяет отслеживать изменения в HTML-документе в режиме реального времени. Без него вам потребовалось бы сначала сохранить документ, а потом обновить страницу с ним в браузере. За работу плагина отвечает кнопка Go Live в нижней строке программы. При нажатии на нее документ, с которым вы работаете автоматически открывается в браузере, который установлен в системе в качестве браузера по умолчанию.

Плагин Live Server в VS Code
SCSS IntelliSense
Плагин показывает дополнительные подсказки при работе с синтаксисом SASS и SCSS. Позволяет автоматизировать некоторые моменты прописывания стилей и указывает на ошибки в синтаксисе, предлагает исправления.
SCSS Formatter
Чем-то похож на предыдущий плагин, но в отличии от него имеет более скромный функционал. Отвечает за корректное форматирование SCSS/SASS.
Better Comments
По умолчанию комментарии в Visual Studio Code отмечены серым цветом и выглядят на фоне основного кода невзрачно. Данный плагин позволяет сделать акцент на комментариях, где это действительно необходимо, например, выделить их контрастным цветом. Цвета выделений можно настроить под себя или использовать стандартный набор. Это очень полезно в случае с командной работой.

Плагин Better Comments в VS Code
BEM Helper
Создан для упрощения работы с BEM. Умеет вставлять сразу новый элемент по методологии bem, учитывая родителя, учитывая блок. Также может вставлять модификаторы, формировать файлы стилей. Будет полезен не только верстальщикам, но и обычным программистам.

Плагин BEM Helper в VS Code
eCSStractor
Этот плагин упрощает перенос классов из HTML в файлы со стилями: CSS, SCSS, SASS. После добавления плагина в программу нужно будет настроить для него сочетание клавиш. Перейдите в его настройки на странице добавления и выберите пункт “Сочетание клавиш”. Задайте любую удобную комбинацию клавиш.
Плагин работает таким образом:
1. Выделите нужный отрезок HTML-кода, из которого требуется скопировать классы.
2. Воспользуйтесь тем сочетанием клавиш, которое вы указали для копирования классов. Вы должны получить сообщение о том, что классы успешно скопировались.

Плагин eCSStractor в VS Code
CSS Navigation
Многофункциональный плагин, связывающий файлы со стилями с другими файлами. Благодаря этому гораздо проще присваивать новые классы элементам, так как появляются специальные подсказки. Еще плагин позволяет очень быстро перемещаться между разметкой и нашими файлами стилей. Дополнительно можно просматривать стили всех совпадающих классов и быстро их редактировать.

Плагин CSS Navigation в VS Code
Image Preview
В процессе верстки часто приходится работать с изображениями — это могут быть как отдельные картинки, так и фоновые изображения, вставленные в файлы со стилями. Плагин позволят увидеть миниатюру нужного изображения, подведя курсором мыши по адресу расположения картинки в коде.

Плагин Image Preview в VS Code
Заключение
На этом рабочая среда Visual Studio Code полностью готова к работе с проектами верстальщика и программиста. Несмотря на то, что редактор кода сам по себе имеет достаточно мощный функционал, разработчик может не только настроить его под свои потребности, но и расширить за счет дополнительных плагинов. Вы необязательно должны устанавливать все плагины из статьи, но они сильно облегчат разработку, особенно больших проектов.