Как отформатировать код в visual studio
Перейти к содержимому

Как отформатировать код в visual studio

  • автор:

Редактор кода в Visual Studio

До сих пор мы рассказывали о том, как начать работу с системой Visual Studio 2013 и как удобно настроить интегрированную систему разработки. Далее мы научим вас эффективно использовать некоторые встроенные команды, комбинации клавиш, а также вспомогательные инструментальные окна. Это поможет вам писать программы и проектировать формы.

Разработчики проводят значительное время, работая над текстами программ. Следовательно, очень важно уметь правильно скомпоновать код и перемещаться по его тексту. В системе Visual Studio 2013 реализован совершенно новый редактор кода, основанный на платформе визуализации WPF (Windows Presentation Foundation). Он предоставляет разработчикам множество новых возможностей в дополнение к тем, которые были унаследованы от предыдущих версий системы.

Компоновка окна редактора кода

Открывая исходный файл для редактирования, вы работаете с окном редактора кода, показанным на рисунке ниже. Основой этого окна является окно кода, в котором отображается текст программы:

Редактор кода Visual Studio

Над окном кода расположены два раскрывающихся списка, которые помогут вам перемещаться по файлу кода. В первом из этих списков перечислены классы, содержащиеся в файле кода, а во втором — члены класса, выбранного из первого списка. Классы и их члены перечислены в алфавитном порядке. Это облегчает поиск метода или определения члена класса в файле.

Когда вы редактируете программу в окне редактора кода, строки кода, которые были модифицированы с момента открытия файла, сопровождаются метками в левом поле — желтыми для несохраненных изменений и зелеными для сохраненных.

Подсветка изменений в коде в Visual Studio

Регионы кода

Класс считается разработанным правильно, если он предназначен для единственной цели и не слишком сложный или длинный. Однако в некоторых ситуациях вы будете вынуждены реализовать так много интерфейсов, что ваш файл кода станет громоздким. Существует множество возможностей, позволяющих справиться с этой задачей, например, разделить код на фрагменты, записанные в разных файлах, или свернуть его фрагменты с помощью регионов (regions), облегчив навигацию по программе.

Использование частичных классов (т.е. классов, определение которых разбросано по нескольким файлам) позволяет в ходе проектирования записывать код в физически разные файлы, которые в совокупности представляют собой логически единый класс. Преимущество использования отдельных файлов заключается в эффективном группировании всех связанных друг с другом методов, например, методов, реализующих интерфейс. В то же время эта стратегия имеет недостаток: перемещение по коду требует постоянного переключения между его файлами.

В качестве альтернативы можно использовать именованные регионы кода (code regions), позволяющие сворачивать разделы кода, которые в данный момент не используются. На рисунке ниже показан один регион кода. Если щелкнуть на знаке «минус», расположенном ниже директивы #region, то можно сжать регион в одну строку, а если на знаке «плюс» — то снова развернуть его:

Использование регионов кода в Visual Studio

Не обязательно разворачивать регион, чтобы увидеть код, который в нем записан. Просто переместите курсор мыши над регионом; и вы увидите код в контекстном окне указателя.

Сворачивание кода

Кроме регионов, которые необходимо определять вручную, в системе Visual Studio 2013 есть структуры кода (outlines), позволяющие автоматически сворачивать методы, комментарии и определения классов. Режим автоматического сворачивания включен по умолчанию. Если он был отключен, то его можно снова включить с помощью команды Edit —> Outlining —> Start Automatic Outlining.

На рисунке ниже показаны четыре сворачиваемых региона. Один из них называется Constructor, а остальные три автоматические структуры кода позволяют свернуть класс, XML-комментарии и метод конструктора (который был сжат). Автоматические структуры можно сворачивать и разворачивать так же, как и регионы, которые определяются вручную.

Пример использования структур кода в Visual Studio

Меню Edit —> Outlining содержит большое количество команд, помогающих переключать режимы сворачивания, то сжимая весь файл до определений методов и свойств (Edit —> Outlining —> Collapse to Definitions), то разворачивая все свернутые фрагменты кода вновь (Edit —> Outlining —> Stop Outlining). Другой способ разворачивать и сворачивать регионы основан на использовании комбинации клавиш <Ctrl+M>, <Ctrl+M> . Эта комбинация позволяет переключаться между двумя режимами.

Разработчикам, работающим на языке C# , знаком трюк, основанный на комбинации клавиш <Ctrl+]> , которая позволяет легко перемещаться от конца региона, фрагмента или блока к его началу, и наоборот.

Форматирование кода

По умолчанию система Visual Studio 2013 помогает писать читабельный код, автоматически выравнивая текст. Однако ее можно настроить так, чтобы контролировать внешний вид кода. Общим для всех языков программирования является возможность управлять событиями, которые должны произойти при создании новой строки. На рисунке ниже показан узел Tabs, расположенный под узлом Text Editors All Languages диалогового окна Options. В этом узле определены значения, заданные по умолчанию для всех языков. Эти значения можно изменить, используя узел Basic —> Tabs (для языка VB.NET), C# —> Tabs, или другие узлы, соответствующие другим языкам.

Настройка выравнивания кода в редакторе в Visual Studio

По умолчанию для языков C# и VB.NET включен режим интеллектуального выравнивания, который, помимо прочего, автоматически осуществляет выравнивание при открытии и закрытии вложений. Интеллектуальное выравнивание доступно не для всех языков. В таких ситуациях вместо него используется выравнивание блоков.

Если вы работаете с маленьким экраном, то, возможно, захотите уменьшить шаги табуляции и размеры отступов, чтобы оптимизировать использование экрана. Задавая шаги табуляции и размеры отступов одинаковыми, вы легко сможете выравнивать свой код с помощью клавиши табуляции. Интересно, что это диалоговое окно дает разработчикам, работающим на языке C#, много возможностей для управления компоновкой своего кода. В узле VB Specific есть только один флажок Pretty listing (reformatting) of code, который при включении позволяет поддерживать единообразный внешний вид кода и освобождает пользователя от необходимости заботиться о методах выравнивания, свертках, определениях классов и пространствах имен. С другой стороны, разработчики, работающие на языке C#, могут контролировать практически каждый аспект форматирования кода с помощью дополнительных узлов.

Режим Smart Indenting в системе Visual Studio практически всегда прекрасно справляется с автоматическим выравниваем кода по мере его ввода или вставки в окно редактора кода, но иногда встречаются плохо отформатированные фрагменты кода, которые трудно читать. Для того чтобы система Visual Studio переформатировала весь документ и установила позиции фигурных скобок и отступов строк, выберите команду Edit —> Advanced —> Format Document или нажмите комбинацию клавиш <Ctrl+K>, <Ctrl+D> . Для того чтобы переформатировать только что выделенный блок кода, выберите команду Edit —> Advanced —> Format Selection или нажмите комбинацию клавиш <Ctrl+K>, <Ctrl+F> .

Для того чтобы выровнять целый блок кода на одном уровне, не изменяя каждую строку по отдельности, выберите блок и нажмите клавишу <Tab> . В начало каждой строки будет вставлен символ табуляции. Для того чтобы отменить выравнивание блока по одному уровню, выделите его и нажмите комбинацию клавиш <Shift+Tab> .

Вы могли заметить, что команды Tabify/Untabify Selected Lines в меню Edit —> Advanced сильно отличаются от команды Format Selection. Эти команды превращают ведущие пробелы в символы табуляции, и наоборот, а не вычисляют заново отступы, как это делает команда Format Selection.

Перемещение вперед и назад по коду

Когда вы перемещаетесь по элементам интерфейса и между ними, система Visual Studio 2013 отслеживает вашу позицию почти так же, как веб-браузер отслеживает сайты, которые вы посетили. Используя команды Navigate Forward и Navigate Backward из меню View, вы сможете легко перемещаться вперед и назад между разными элементами проекта, в которые внесли изменения. Для перемещения назад используется комбинация клавиш <Ctrl+-> , а для перемещения вперед — <Ctrl+Shift+-> .

Дополнительные свойства редактора кода

Редактор кода в системе Visual Studio имеет очень много возможностей, которые трудно исчерпывающим образом описать в этой статье. Однако наиболее полезные из них мы приводим ниже.

Подсветка ссылок

Подсветка ссылок — интересное свойство системы Visual Studio, которое появилось в версии 2010. Система выделяет все вхождения имени элемента кода в области видимости (например, имени метода или свойства), на которое указывает курсор. Благодаря этому легче будет найти места, где это имя еще используется в коде. Вы сможете легко перемещаться между этими местами с помощью комбинации клавиш <Ctrl+Shift+Up/Down> .

Подсветка ссылок в редакторе кода Visual Studio

Укрупнение кода

С помощью комбинации <Ctrl+Mouse Wheel> можно увеличивать и уменьшать масштаб кода (по существу, увеличивая и уменьшая текст). Это свойство может оказаться особенно полезным, когда необходимо продемонстрировать код группе людей. В левом нижнем углу окна редактора кода есть раскрывающийся список, позволяющий выбрать заранее заданные уровни увеличения текста.

Сворачивание текста

Чтобы включить опцию сворачивания текста в окне редактора кода, выберите команду Tools —> Options, откройте узел Text Editor, выберите подузел All Languages и установите флажок Word Wrap. Можете также отобразить глиф стрелки возврата (return arrow) в том месте, где текст должен быть свернут, установив флажок Show Visual Glyphs for Word Wrap, расположенный ниже флажка Word Wrap.

Чтобы применить эти установки к текущему проекту, выберите команду Edit —> Advanced —> Word Wrap.

Номера строк

Для того чтобы отслеживать положение курсора в файле, полезно пронумеровать строки в окне редактора кода. Для того чтобы включить режим нумерации строк, выберите команду меню Tools —> Options, откройте узел Text Editor, выберите узел All Languages и установите флажок Numbers:

Нумерация строк кода в Visual Studio

Разделение окна

Иногда нужно разделить один и тот же файл кода на две части и просматривать одновременно в разных окнах. Можете разделить активное окно редактора на верхнюю и нижнюю части с помощью линии разбивки (splitter bar). Эти окна можно прокручивать независимо друг от друга и отображать в них содержимое одного и того же файла в одно и то же время.

Разделение редактора кода на два окна в Visual Studio

Для того чтобы разделить окно редактора кода, выберите команду Split из меню Window. В качестве альтернативы можно перетащить метку манипулятора (расположенную прямо над панелью вертикальной прокрутки), в позицию, где должна располагаться линия разбивки.

Чтобы настроить размеры каждого окна, достаточно передвинуть линию разбивки вверх или вниз. Удалить линию разбивки просто: дважды щелкните на ней или выберите команду Remove Split из меню Window.

Свободное перемещение окон редактора кода

В версии Visual Studio 2010 появилось новшество, которого долго ожидали программисты, работающие с несколькими дисплеями, — возможность «освобождать» окна редактора кода (и инструментальные окна) и перемещать их за пределы главного окна системы Visual Studio (как показано на рисунке ниже) и даже на другой дисплей. Это позволяет одновременно работать с несколькими окнами редактора кода, расположенными на разных дисплеях. Для того чтобы освободить окно, сначала убедитесь, что оно находится в фокусе, а затем выберите команду Float из окна Window. В качестве альтернативы можно щелкнуть правой кнопкой мыши на заголовке окна и выбрать команду Float из контекстного меню или щелкнуть и перетащить закладку для этого окна (при этом окно освобождается) и перетащить его в то место, где вы хотите его расположить.

Пример свободного перемещения нескольких окон Visual Studio

Когда разделение окна редактора кода на две части для одновременного просмотра разных фрагментов одного и того же файла (см. предыдущий раздел) оказывается неудобным, можно вместо этого использовать плавающее окно, разместив его, например, на другом дисплее (если вы работаете с несколькими дисплеями). Для этого можно воспользоваться специальным трюком (поскольку двойной щелчок мышью на файле в окне Solution Explorer просто активизирует существующее окно редактора кода для данного файла) — выбрать команду New Window в меню Window. Эта команда откроет просматриваемый в данный момент файл в новом окне, которое можно сделать свободным и разместить в любом месте.

Создание групп закладок

Если у вас нет нескольких мониторов, то все равно есть возможность открыть одновременно несколько окон редактора кода. Для этого следует создать группы закладок и создать из них мозаику, чтобы отобразить одновременно. Каждая закладка окна редактора кода в этой группе отображается как отдельный элемент мозаики. Таким образом, можно создать несколько групп закладок. Их количество ограничено лишь размерами экрана, на котором они должны размещаться. Элементы мозаики можно размещать как вертикально, так и горизонтально, правда, применить эти два способа одновременно невозможно.

Для того чтобы начать этот процесс, откройте в окне редактора кода несколько закладок. Убедитесь, что закладка окна редактирования кода находится в фокусе, а затем выберите команду Window —> New Horizontal Tab Group или Window —> New Vertical Tab Group из открывшегося меню. В результате будет создана новая группа закладок и мозаика для них:

Создание нескольких групп закладок редактора кода в Visual Studio

В качестве альтернативы можно просто перетащить закладку вниз или за существующую и прикрепить ее в этой позиции, получив тот же самый результат. Можно также перетаскивать закладки из одной группы закладок в другую, используя команды Window —> Move to Next Tab Group и Window —> Move to Previous Tab Group. Эти команды доступны также в меню, которое открывается после щелчка правой кнопкой мыши на закладке. Для того чтобы восстановить пользовательский интерфейс, имеющий только одну группу закладок, переместите закладки из новой группы (или групп) закладок назад в исходное место, и мозаика исчезнет.

Несколько панелей Solution Explorer

Если вы работаете на нескольких мониторах, то в версиях Visual Studio 2008 и ниже вы могли заметить, что нельзя открыть несколько панелей Solution Explorer. В Visual Studio 2013 этого ограничения не существует. Щелкните на одном из элементов в окне Solution Explorer правой кнопкой мыши и выберите в контекстном меню команду New Solution Explorer view. При выборе этой команды откроется новое окно Solution Explorer, которое будет содержать выбранный элемент. Это очень удобно при работе на нескольких мониторах.

Несколько панелей Solution Explorer в Visual Studio

Дополнительные возможности

Для того чтобы достичь действительно высокой производительности труда, полезно знать о многочисленных скрытых возможностях редактора кода, которые позволяют сэкономить массу времени. Рассмотрим некоторые из наиболее полезных команд, которые скрыты в редакторе кода.

«Закомментирование» и «раскомментирование» блока кода

Часто возникает необходимость «закомментировать» блок кода или «раскомментировать» его. При этом не хотелось бы добавлять символы комментариев в начало каждой строки или удалять их оттуда, особенно, если этих строк в блоке много. Разумеется, в языке C# можно свернуть блок кода, разместив его между символами /* и */, чтобы «закомментировать», но такой тип комментариев в языке Visual Basic отсутствует. Кроме того, даже в языке C# возникают проблемы, когда требуется «закомментировать» блок, который уже содержит в себе подобные комментарии.

В системе Visual Studio есть простое средство для «закомментирования» и «раскомментирования» блоков. Для этого следует выделить блок, затем выбрать команду Edft —> Advanced —> Comment Selection, чтобы «закомментировать» его, или Edit —> Advanced —> Uncomment Selection, чтобы «раскомментировать» его. Проще всего выбрать эти команды (скорее всего, именно их вы будете чаще всего использовать) с помощью комбинаций клавиш. Нажмите комбинации клавиш <Ctrl+K>, <Ctrl+C> , чтобы «закомментировать» блок кода, и <Ctrl+K>, <Ctrl+U> — чтобы «раскомментировать» его. Еще одним простым средством для доступа к этим командам является инструментальная панель Text Editor.

Выделение блока

Выделение блока, которое называют также выделением окна (box selection), столбца (column selection), прямоугольника (rectangle) или вертикального текста (vertical text selection), как показано на рисунке ниже, подразумевает выделение текстового блока, а не строк (процедура, которая называется выделением потока (stream selection)). Для того чтобы отметить текстовый блок, нажмите клавишу <Alt> и не отпускайте ее, пока выделяете текст мышью, или используйте комбинацию клавиш <Shift+Alt+Arrow> . Это свойство может оказаться полезным, когда необходимо удалить часть вертикально выровненного кода (например, префикс в объявлениях переменных):

Выделение столбца кода в редакторе Visual Studio

Многострочное редактирование

Многострочное редактирование — это новое свойство, появившееся в системе Visual Studio 2010 и расширяющее возможность выделения блоков. В предыдущих версиях системы после выделения вертикального текстового блока вы могли только удалять, вырезать или копировать блок. Теперь в системе Visual Studio после выделения вертикального текстового блока можно в каждой строке набрать текст, который заменит выделенный фрагмент. Это удобно, например, когда требуется заменить уровень доступа к группе переменных с private на protected.

Многострочное редактирование в Visual Studio

Можно также вставить текст одновременно в несколько строк, создав блок с нулевой шириной и просто начав печатать.

Кольцевой буфер обмена

Система Visual Studio отслеживает последние двадцать фрагментов текста, которые были скопированы или вырезаны в буфер обмена. Для того чтобы вставить текст, который был ранее скопирован в буфер обмена, но был перезаписан, вместо обычной комбинации <Ctrl+V> , предназначенной для вставки, можно использовать комбинацию <Ctrl+Shift+V> . Нажав клавишу <V> и удерживая клавиши <Ctrl+Shift> , можно выполнять циклы просмотра элементов буфера обмена.

Полноэкранный режим

Можете максимизировать представление кода, подлежащего редактированию, выбрав команду View —> Full Screen или нажав комбинацию клавиш <Shift+Alt+Enter> , чтобы увеличить до максимума окно редактора кода, скрыв другие инструментальные окна и панели. Для того чтобы вернуться в обычный режим, снова нажмите комбинацию клавиш <Shift+Alt+Enter> или щелкните на кнопке переключения Full Screen, добавленной в конце панели меню.

Переход к определению

Для того чтобы быстро перейти к определению класса, метода или члена, расположенного ниже курсора, щелкните правой кнопкой мыши и выберите команду Go То Definition или нажмите клавишу <F12> .

Поиск всех ссылок

В системе Visual Studio 2013 есть возможность найти точку вызова метода или ссылки на свойство, щелкнув правой кнопкой мыши на его определении и выбрав команду Find All References в контекстном меню или поместив курсор на определение метода и нажав комбинацию клавиш <Shift+F12> . Эти команды открывают инструментальное окно Find Symbol Results, содержащее позиции, в которых существуют ссылки на указанный метод или свойство. Теперь можно дважды щелкнуть на ссылке в окне результатов, чтобы переместиться на искомую позицию в окне редактирования кода.

Это свойство несколько устарело после появления нового окна Call Hierarchy, которое будет рассмотрено позже. Однако оно по-прежнему позволяет быстро находить используемый метод без перемещения по окну Call Hierarchy.

Visual Studio Code Formatting Setup

Our team has multiple software engineers working on the same codebase, formatting code sometimes becomes an issue. Depending on the editor setup, the same code working for one person might be automatically formatted by another, which results in PR often with lot of formatting changes.

The solution is to use the same formatting rules and tools across the team so the code format is standardized.

Since we mainly develop Angular application in TypeScript/HTML/Sass, below I’m going to show you my code formatting setup for those file types.

Also, the underline formatting tool VS Code uses is listed below, so if you are using other editors, you might be able to achieve the same format result.

How to format code

You can format manually or enable format on save.

  • To format manually, press SHIFT+CMD+P then type ‘format’, select ‘format document’ or ‘format selection’. Or, just press SHIFT+ALT+F
  • To enable format on save, add this line to your settings: ”editor.formatOnSave”: true

Format TypeScript

TypeScript is supported by default.

Underline, VS Code is using js-beautify.

However, imports are not sorted by formatting. We can use “Typescript Hero” extension to automatically sort the imports.

  • To sort the imports manually, press SHIFT+CMD+P then type ‘imports’, hit ENTER on the first command.
  • To sort on save, add this to your settings: “typescriptHero.imports.organizeOnSave”: true

Format HTML

HTML formatting is supported by default.

Underline, VS Code is using js-beautify.

Please refer here for settings.

Format Sass

VS Code has default support for SASS but we can also install ‘Sass Formatter’ extension for better support.

Underline, ‘Sass Formatter’ use ‘sass-convert’ so vim user should be able to achieve the same functionality.

This post belongs to a series “Know your editor: Visual Studio Code”, where it has a collection of Visual Studio Code tips and setup.

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.

    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, Linux Ctrl+Shift+J ) ). This will show additional fields to configure the search.

    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 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.

    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, 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:

    Search Editor overview

    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.

    Folding

    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:

    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 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.

    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

    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.

    global search and replace

    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:

    How do you format code in Visual Studio Code (VSCode)?

    What is the equivalent of Ctrl + K + F and Ctrl + K + D on Windows in Visual Studio for formatting, or «beautifying» code in the Visual Studio Code editor?

    Baum mit Augen's user avatar

    29 Answers 29

    The code formatting is available in Visual Studio Code through the following shortcuts:

    • On Windows Shift + Alt + F
    • On Mac Shift + Option + F
    • On Linux Ctrl + Shift + I

    Alternatively, you can find the shortcut, as well as other shortcuts, through the submenu View / Command Palette , also provided in the editor with Ctrl + Shift + P (or Command + Shift + P on Mac), and then searching for format document.

    For unsaved snippets

    Open command palette (Win: F1 or Ctrl + Shift + P )

    Find "Change Language Mode"

    Select language e.g. json . By now syntax should be highlighted.

    Format document (e.g. Open Command Palette -> "Format Document")

    Unformat

    1. Select text
    2. Command Palette -> Join Lines

    Show the pics

    enter image description here enter image description here

    Code Formatting Shortcut:

    Visual Studio Code on Windows — Shift + Alt + F

    Visual Studio Code on MacOS — Shift + Option + F

    Visual Studio Code on Ubuntu — Ctrl + Shift + I

    You can also customize this shortcut using a preference setting if needed.

    Code Formatting While Saving the File:

    Visual Studio Code allows the user to customize the default settings.

    If you want to auto format your content while saving, add the below code snippet in the work space settings of Visual Studio Code.

    Menu FilePreferencesWorkspace Settings

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *