Visual studio code format code
Visual studio code format code
Options dialog box: Text Editor > C# > Code Style > Formatting
Use the Formatting options page and its subpages (Indentation, New Lines, Spacing, and Wrapping) to set options for formatting code in the code editor.
To access this options page, choose Tools > Options from the menu bar. In the Options dialog box, choose Text Editor > C# > Code Style > Formatting.
The Indentation, New Lines, Spacing, and Wrapping subpages each display a preview window at the bottom that shows the effect of each option. To use the preview window, select a formatting option. The preview window shows an example of the selected option. When you change a setting by selecting a radio button or check box, the preview window updates to show the effect of the new setting.
Formatting (General) page
General settings
These settings affect when the code editor applies formatting options to code.
Label | Description |
---|---|
Automatically format when typing | When deselected, the format statement on ; and format block on > options are disabled. |
Automatically format statement on ; | When selected, formats statements at completion according to the formatting options selected for the editor. |
Automatically format block on > | When selected, formats code blocks according to the formatting options selected for the editor as soon as you complete the code block. |
Automatically format on return | When selected, formats text when Enter is pressed, to fit the formatting options selected for the editor. |
Automatically format on paste | When selected, formats text that is pasted into the editor to fit the formatting options selected for the editor. |
If you previously applied code style settings for C# files using the Format Document command in Visual Studio 2017, that functionality is now available as Code Cleanup.
Indentation page
The indentation options on this page apply when code is formatted automatically. One example of when code is automatically formatted is when you paste code into the file while Automatically format on paste is selected. (The Automatically format on paste option is under Formatting > General.)
There are also indentation options on the Text Editor > C# > Tabs options page. Those options only determine where the code editor places the cursor when you press Enter at the end of a line.
New Lines page
Use the new lines options on this page to control whether you want braces, keywords, or expressions to appear on new lines in the code editor.
How to format code in Visual Studio Code on Windows
How can I format code in Visual Studio Code in the last update on Windows.
I tried the following solution, but that is not the issue:
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you are working on PHP you should download the PHP extension format code.
Press F1 and type:
Then Shift + Alt + F will work.
You can also select the code you want to format and right click, find the format code menu item and it should have the keyboard command listed next to it.
Simply use Ctrl + Shift + I
Or
Right Click on document and Click on Format Document
If it’s for JavaScript, JSON, CSS, Sass, and HTML, there no better way than the Beautify extension. It is simple and very useful!
Once installed the way you do it are described here with good illustrations (to avoid content duplication): How can I format PHP files with HTML markup in Visual Studio Code?
For others languages, you add the appropriate extensions and you can set keybinding (you need to get the appropriate command to execute, and add the keybinding to keybindings.json). I have explained that in the link above. Always read well the documentation of the extensions. There you can find all the possible configurations and so.
For specific languages you can search via Visual Studio Code in the extension marketplace. Enter just Beautify and you will see all the different Beautify extensions for the different languages. Also you can use formatting format formatter keywords, like PHP formatting and so.
Also, you can use the integrated formatting tool of Visual Studio Code. Mostly by clicking right and selecting formatting document, you can also format just a selection.
Here is the shortcut for formatting the whole document:
How To Format Code with Prettier in Visual Studio Code
Introduction
Formatting code consistently is a challenge, but modern developer tools make it possible to automatically maintain consistency across your team’s codebase.
In this article, you’ll set up Prettier to automatically format your code in Visual Studio Code, also known as VS Code.
For demonstration purposes, here’s the sample code you will be formatting:
If you’re familiar with code formatting, you may notice some missteps:
Prerequisites
To follow this tutorial, you will need to download and install Visual Studio Code.
Step 1 — Using the Format Document Command
With the Prettier extension installed, you can now leverage it to format your code. To start, let’s explore using the Format Document command. This command will make your code more consistent with formatted spacing, line wrapping, and quotes.
To open the command palette, you can use COMMAND + SHIFT + P on macOS or CTRL + SHIFT + P on Windows.
In the command palette, search for format and then choose Format Document.
You may then be prompted to choose which format to use. To do so, click the Configure button:
Your code is now formatted with spacing, line wrapping, and consistent quotes:
This also works on CSS files. You can turn something with inconsistent indentation, braces, new lines, and semicolons into well-formatted code. For example:
Will be reformatted as:
Now that we’ve explored this command, let’s look at how this can me implemented to run automatically.
Step 2 — Formatting Code on Save
So far, you’ve had to manually run a command to format your code. To automate this process, you can choose a setting in VS Code to have your files automatically formatted when you save. This also ensures that code doesn’t get checked to version control that’s not formatted.
Once this is set, you can write your code as usual and it will be automatically formatted when you save the file.
Step 3 — Changing the Prettier Configuration Settings
Prettier does a lot of things for you by default, but you can also customize the settings.
Open the Settings menu. Then, search for Prettier. This will bring up all of the settings that you can change:
Here are a few of the most common settings:
The downside to using the built-in settings menu in VS Code is that it doesn’t ensure consistency across developers on your team.
Step 4 — Creating a Prettier Configuration File
If you change settings in your VS Code, someone else could have an entirely different configuration on their machine. You can establish consistent formatting across your team by creating a configuration file for your project.
Here’s an example of a simple configuration file using JSON:
For more specifics on the configuration files, check out the Prettier Docs. After creating one of these and checking it into your project, you can ensure that every team member follows the same formatting rules.
Conclusion
Having consistent code is a good practice. It is particularly beneficial when working on a project with multiple collaborators. Agreeing upon a set of configurations helps with legibility and understanding of code. More time can be devoted to solving challenging technical problems instead of wrestling over solved problems like code indentation.
Prettier ensures consistency in your code formatting and makes the process automatic.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
How do you change the formatting options in Visual Studio Code?
I know you can Format Code using Ctrl + F / Cmd + F in Visual Studio Code but how do you change the formatting options for each language?
For example, in Visual Studio 2013 I can choose compact mode for CSS.
Is there another hidden JSON file to do that?
8 Answers 8
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Update 2022
Solution A:
Press Ctrl + Shift + P
Then type Format Document With.
At the end of the list click on Configure Default Formatter.
Now you can choose your favorite beautifier from the list.
Solution B:
If we are talking Visual Studio Code nowadays you set a default formatter in your settings.json :
Point to the identifier of any installed extension, i.e.
You can also do so format-specific:
You could also assign other keys for different formatters in your keyboard shortcuts ( keybindings.json ). By default, it reads:
I just found this extension called beautify in the Market Place and yes, it’s another config\settings file. 🙂
Beautify javascript, JSON, CSS, Sass, and HTML in Visual Studio Code.
Edit:
This is now supported (as of 2019). Please see sajad saderi’s answer below for instructions.
No, this is not currently supported (in 2015).
You can make some changes from the «Settings». For example javascript rules start with «javascript.format». But for advanced formatting control, still need to use some extensions.
A solution that works for me (July 2017), is to utilize ESLint. As everybody knows, you can use the linter in multiple ways, globally or locally. I use it locally and with the google style guide. They way I set it up is as follow.
Edit C++ in Visual Studio Code
This topic provides a quick overview of general C/C++ editor features, as well as some that are specific to C/C++. For more information about editing in Visual Studio Code, see Basic Editing and Code Navigation.
The C/C++ extension supports Remote Development.
Editing features
The C/C++ extension for VS Code has many features that help you write code, understand it, and navigate around in your source files. To provide the best experience, the extension needs to know where it can find each header file referenced in your code. By default, the extension searches the current source directory, its sub-directories, and some platform-specific locations. If a referenced header file can’t be found, VS Code displays a green squiggle underneath each #include directive that references it.
To specify additional include directories to be searched, place your cursor over any #include directive that displays a green squiggle, then click the lightbulb action when it appears. This opens the file c_cpp_properties.json for editing; here you can specify additional include directories for each platform configuration individually by adding more directories to the ‘browse.path’ property.
List members
Code formatting
The C/C++ extension for Visual Studio Code supports source code formatting using clang-format which is included with the extension.
The Visual Studio clang-format style is not yet an official clang-format style but it implies the following clang-format settings:
To use a different version of clang-format than the one that ships with the extension, change the C_Cpp.clang_format_path setting to the path where the clang-format binary is installed.
For example, on the Windows platform:
Enhanced semantic colorization
When IntelliSense is enabled, the Visual Studio Code C/C++ extension supports semantic colorization. See Enhanced colorization for more details about setting colors for classes, functions, variables and so on.
Quick Info
You can hover over a symbol to see an inline view of its definition:
Peek Definition
The Peek Definition feature displays a few lines of code near the definition inside a peek window, so that you don’t have to navigate away from your current location.
Currently, the C/C++ extension doesn’t parse code in a way that helps it distinguish between competing definitions based on how the symbol is used. These competing definitions arise when the symbol defines different things in different contexts, such as occurs with overloaded functions, classes and their constructors, and other situations. When this happens, each of the competing definitions is listed in the right-hand side of the peek window with the source code of the current selection displayed on the left.
With the peek window open, you browse the list of competing definitions to find the one you’re interested in. If you want to navigate to the location of one of the definitions just double-click the definition you’re interested in, or by double-clicking anywhere in the source code displayed on the left-hand side of the peek window.
Navigate source code
The source code navigation features provided by the C/C++ extension are powerful tools for understanding and getting around in your codebase. These features are powered by tags stored in a local database of symbol information. With the C/C++ extension installed, this database is generated whenever a folder containing C++ source code files is loaded into VS Code. The database icon appears next to the active configuration name («Win32» in the image below) while the tag-parser is generating this information.
The icon disappears when all the symbols have been tagged.
Search for symbols
You can search for symbols in the current file or workspace to navigate your code more quickly.
You can also search for symbols by accessing these commands through the Command Palette. Use Quick Open ( ⌘P (Windows, Linux Ctrl+P ) ) then enter the ‘@’ command to search the current file, or the ‘#’ command to search the current workspace. ⇧⌘O (Windows, Linux Ctrl+Shift+O ) and ⌘T (Windows, Linux Ctrl+T ) are just shortcuts for the ‘@’ and ‘#’ commands, so everything works the same.
Go to Definition
You can also quickly navigate to where a symbol is defined by using the Go to Definition feature.
Next steps
Read on to find out about:
If you have any other questions or run into any issues, please file an issue on GitHub. You may be asked to provide logging information from the extension to help diagnose the issue. See C/C++ extension logging for help on providing extension logs.
Code style preferences
You can define code style settings per-project by using an EditorConfig file, or for all code you edit in Visual Studio on the text editor Options page. For C# code, you can also configure Visual Studio to apply these code style preferences using the Code Cleanup (Visual Studio 2019, Visual Studio 2022) and Format Document (Visual Studio 2017) commands.
This topic applies to Visual Studio on Windows. For Visual Studio for Mac, see Editor behavior in Visual Studio for Mac.
Code styles in EditorConfig files
Code styles in the Options dialog box
Code style preferences can be set for all of your C# and Visual Basic projects by opening the Options dialog box from the Tools menu. In the Options dialog box, select Text Editor > [C# or Visual Basic] > Code Style > General.
Code style preferences can be set for all of your C# and Visual Basic projects by opening the Options dialog box from the Tools menu. In the Options dialog box, select Text Editor > [C# or Basic] > Code Style > General.
Each item in the list shows a preview of the preference when selected:
Preference and severity
For each code style setting on this page, you can set the Preference and Severity values using the drop-downs on each line. Severity can be set to Refactoring Only, Suggestion, Warning, or Error. If you want to enable Quick Actions for a code style, ensure that the Severity setting is set to something other than Refactoring Only. The Quick Actions light bulb , error light bulb
, or screwdriver
icon appears when a non-preferred style is used, and you can choose an option on the Quick Actions list to automatically rewrite code to the preferred style.
Enforce code styles on build
Apply code styles
For C# code files, Visual Studio has a Code Cleanup button at the bottom of the editor (keyboard: Ctrl+K, Ctrl+E) to apply code styles from an EditorConfig file or from the Code Style options page. If an .editorconfig file exists for the project, those are the settings that take precedence.
Rules configured with a severity of None don’t participate in code cleanup but can be individually applied via the Quick Actions and Refactorings menu.
First, configure which code styles you want to apply (in one of two profiles) in the Configure Code Cleanup dialog box. To open this dialog box, click the expander arrow next to the code cleanup broom icon and then choose Configure Code Cleanup.
After you’ve configured code cleanup, you can either click on the broom icon or press Ctrl+K, Ctrl+E to run code cleanup. You can also run code cleanup across your entire project or solution. Right-click on the project or solution name in Solution Explorer, select Analyze and Code Cleanup, and then select Run Code Cleanup.
For C# code files, Visual Studio has a Code Cleanup button at the bottom of the editor (keyboard: Ctrl+K, Ctrl+E) to apply code styles from an EditorConfig file or from the Code Style options page. If an .editorconfig file exists for the project, those are the settings that take precedence.
Rules configured with a severity of None don’t participate in code cleanup but can be individually applied via the Quick Actions and Refactorings menu.
First, configure which code styles you want to apply (in one of two profiles) in the Configure Code Cleanup dialog box. To open this dialog box, click the expander arrow next to the code cleanup broom icon and then choose Configure Code Cleanup.
After you’ve configured code cleanup, you can either click on the broom icon or press Ctrl+K, Ctrl+E to run code cleanup. You can also run code cleanup across your entire project or solution. Right-click on the project or solution name in Solution Explorer, select Analyze and Code Cleanup, and then select Run Code Cleanup.
Code cleanup settings
Setting | Rule ID or style option |
---|---|
Remove unnecessary Imports or usings | IDE0005 |
Apply file header preferences | file_header_template |
Remove unused variables | IDE0051 |
Apply object creation preferences | visual_basic_style_prefer_simplified_object_creation |
Apply IsNot preferences | visual_basic_style_prefer_isnot_expression |
Add ‘this’ or ‘Me’ qualification | IDE0003-IDE0009 |
Add accessibility modifiers | dotnet_style_require_accessibility_modifiers |
Order modifiers | IDE0036 |
Make field readonly | dotnet_style_readonly_field |
Remove unnecessary casts | IDE0004 |
Apply object/collection initialization parameters) | dotnet_style_object_initializer |
Apply using directive placement preferences | csharp_using_directive_placement |
Apply parentheses preferences | IDE0047-IDE0048 |
Apply unused value preferences | IDE0058 |
Apply language/framework type preferences | IDE0049 |
Remove unused suppressions | dotnet_remove_unnecessary_suppression_exclusions |
Apply simplify boolean expression preferences | dotnet_style_prefer_simplified_boolean_expressions |
Apply string interpolation preferences | dotnet_style_prefer_simplified_interpolation |
Remove unused parameters | dotnet_code_quality_unused_parameters |
Apply auto property preferences | dotnet_style_prefer_auto_properties |
Apply compound assignment preferences | dotnet_style_prefer_compound_assignment |
Apply coalesce expression preferences | dotnet_style_coalesce_expression |
Apply conditional expression preferences | dotnet_style_prefer_conditional_expression_over_assignment dotnet_style_prefer_conditional_expression_over_return |
Apply tuple name preferences | dotnet_style_explicit_tuple_names dotnet_style_prefer_inferred_tuple_names |
Apply inferred anonymous type member names preferences | dotnet_style_prefer_inferred_anonymous_type_member_names |
Apply null checking preferences | dotnet_style_prefer_is_null_check_over_reference_equality_method |
Apply null propagation preferences | dotnet_style_null_propagation |
Apply ‘var’ preferences | IDE0007-IDE0008 |
Add required braces for single-line control statements | csharp_prefer_braces |
Apply expression/block body preferences | Expression-bodied members |
Apply inline ‘out’ variables preferences | csharp_style_inlined_variable_declaration |
Apply pattern matching preferences | Pattern-matching preferences |
Apply conditional delegate call preferences | csharp_style_conditional_delegate_call |
Apply static local function preferences | csharp_prefer_static_local_function |
Apply deconstruct preferences | csharp_style_deconstructed_variable_declaration |
Apply default(T) preferences | csharp_prefer_simple_default_expression |
Apply new() preferences | csharp_style_implicit_object_creation_when_type_is_apparent |
Apply range preferences | csharp_style_prefer_range_operator |
Apply local over anonymous function preferences | csharp_style_pattern_local_over_anonymous_function |
Apply parameter null preferences | Null-checking preferences |
Apply using statement preferences | csharp_prefer_simple_using_statement |
Apply throw expression preferences | csharp_style_throw_expression |
If you want your code style settings to be applied every time you save a file, go to Options > Text Editor > Code Cleanup and select Run Code Cleanup profile on save.
If you want your code style settings to be applied every time you save a file, you may like the Code Cleanup on Save extension.
Параметры стиля кода
Код стиля параметров каждого проекта можно определить с помощью EDITORCONFIG-файла; для всего кода в Visual Studio можно задать настройки на странице Параметры в текстовом редакторе. Для кода на C# можно также настроить Visual Studio, чтобы применять эти параметры стиля кода с помощью команд Очистка кода (Visual Studio 2019, Visual Studio 2022) и Форматировать документ (Visual Studio 2017).
Этот раздел относится к Visual Studio в Windows. Информацию о Visual Studio для Mac см. в статье Поведение редактора в Visual Studio для Mac.
Стили кода в EDITORCONFIG-файлах
Вы можете вручную отредактировать файл EditorConfig или автоматически создать его в зависимости от установленных в Visual Studio параметров стиля кода в диалоговом окне Параметры. Эта страница параметров доступна втекстовом редакторе> параметров инструментов> > [C# или Basic] >Code Style>General. Нажмите кнопку Создать EDITORCONFIG-файл из параметров, чтобы автоматически создать EDITORCONFIG-файл стиля кода на основе параметров, которые вы задали на этой странице Параметры.
Вы можете вручную отредактировать файл EditorConfig или автоматически создать его в зависимости от установленных в Visual Studio параметров стиля кода в диалоговом окне Параметры. Эта страница параметров доступна втекстовом редакторе> параметров инструментов> > [C# или Visual Basic] >Code Style>General. Нажмите кнопку Создать EDITORCONFIG-файл из параметров, чтобы автоматически создать EDITORCONFIG-файл стиля кода на основе параметров, которые вы задали на этой странице Параметры.
Стили кода в диалоговом окне «Параметры»
Параметры стиля кода для проектов C# и Visual Basic можно задать, открыв диалоговое окно Параметры из меню Сервис. В диалоговом окне «Параметры» выберите текстовый редактор> [C# или Visual Basic] >«Общий стиль> кода».
Параметры стиля кода для проектов C# и Visual Basic можно задать, открыв диалоговое окно Параметры из меню Сервис. В диалоговом окне «Параметры» выберите текстовый редактор> [C# или Basic] > Code StyleGeneral(Общие) стиль> кода.
При выборе для каждого из элементов в списке выводится окно предварительного просмотра:
Параметры, заданные в этом окне, применяются к вашей учетной записи персонализации Visual Studio и не связаны с конкретным проектом или базой кода. Кроме того, они не применяются во время сборки, в том числе в сборках с непрерывной интеграцией (CI). Если вы хотите связать предпочтения к стилю кода со своим проектом и применяете стили во время сборки, укажите такие предпочтения в EDITORCONFIG-файле, связанном с проектом.
Предпочтения и степень серьезности
Для каждого параметра стиля кода на этой странице с помощью раскрывающихся списков в каждой строке можно задать значения для параметров Предпочтение и Серьезность. Для серьезности можно задать значения Только рефакторинг, Предложение, Предупреждение или Ошибка. Если вы хотите включить быстрые действия для стиля кода, убедитесь, что для параметра Серьезность задано значение, отличное от Только рефакторинг. Лампочка быстрых действий, лампочка
ошибки или значок отвертки
появляется, когда используется не предпочтительный стиль, и вы можете выбрать параметр в списке быстрых действий, чтобы автоматически переписать код в предпочитаемый стиль.
Принудительное применение стиля кода в сборке
Применение стилей кода
Для файлов кода на C# в Visual Studio есть кнопка Очистка кода в нижней части редактора (сочетание клавиш: CTRL+K, CTRL+E) для применения стилей кода из EDITORCONFIG-файла или со страницы параметров стиля кода. Если EDITORCONFIG-файл существует в проекте, его параметры имеют приоритет.
Правила, настроенные с серьезностью Нет, не используются в ходе очистки кода, но могут применяться по отдельности через меню Быстрые действия и рефакторинг.
Во-первых, настройте стили кода, которые необходимо применять (в одном из двух профилей), используя диалоговое окно Настройка очистки кода. Чтобы открыть это диалоговое окно, щелкните стрелку рядом со значком метлы (очистка кода) и выберите команду Настроить очистку кода.
После настройки очистки кода вы можете щелкнуть значок метлы или нажать клавиши Ctrl+K, Ctrl+E, чтобы запустить очистку кода. Вы также можете выполнить очистку кода для всего проекта или решения сразу. Щелкните правой кнопкой мыши имя проекта или решения в обозревателе решений, выберите команду Анализ и очистка кода, а затем — Запустить очистку кода.
Для файлов кода на C# в Visual Studio есть кнопка Очистка кода в нижней части редактора (сочетание клавиш: CTRL+K, CTRL+E) для применения стилей кода из EDITORCONFIG-файла или со страницы параметров стиля кода. Если EDITORCONFIG-файл существует в проекте, его параметры имеют приоритет.
Правила, настроенные с серьезностью Нет, не используются в ходе очистки кода, но могут применяться по отдельности через меню Быстрые действия и рефакторинг.
Во-первых, настройте стили кода, которые необходимо применять (в одном из двух профилей), используя диалоговое окно Настройка очистки кода. Чтобы открыть это диалоговое окно, щелкните стрелку рядом со значком метлы (очистка кода) и выберите команду Настроить очистку кода.
После настройки очистки кода вы можете щелкнуть значок метлы или нажать клавиши Ctrl+K, Ctrl+E, чтобы запустить очистку кода. Вы также можете выполнить очистку кода для всего проекта или решения сразу. Щелкните правой кнопкой мыши имя проекта или решения в обозревателе решений, выберите команду Анализ и очистка кода, а затем — Запустить очистку кода.
Параметры очистки кода
Параметр | Параметр «Идентификатор правила» или «Стиль» |
---|---|
Удаление ненужных операций импорта или использования | IDE0005 |
Применение параметров заголовка файла | file_header_template |
Удаление неиспользуемых переменных | IDE0051 |
Применение параметров создания объектов | visual_basic_style_prefer_simplified_object_creation |
Применение параметров IsNot | visual_basic_style_prefer_isnot_expression |
Добавление квалификации «this» или «Me» | IDE0003-IDE0009 |
Добавить модификаторы доступа | dotnet_style_require_accessibility_modifiers |
Модификаторы Order | IDE0036 |
Создание поля только для чтения | dotnet_style_readonly_field |
Удалить лишние операции приведения | IDE0004 |
Применение параметров инициализации объекта или коллекции) | dotnet_style_object_initializer |
Применение параметров размещения директив using | csharp_using_directive_placement |
Применение настроек круглых скобок | IDE0047-IDE0048 |
Применение параметров неиспользуемых значений | IDE0058 |
Применить настройки типа языка или платформы | IDE0049 |
Удаление неиспользуемых подавлений | dotnet_remove_unnecessary_suppression_exclusions |
Применение логического выражения | dotnet_style_prefer_simplified_boolean_expressions |
Применение параметров интерполяции строк | dotnet_style_prefer_simplified_interpolation |
Удаление неиспользуемых параметров | dotnet_code_quality_unused_parameters |
Применение параметров автоматического свойства | dotnet_style_prefer_auto_properties |
Применение параметров составного назначения | dotnet_style_prefer_compound_assignment |
Применение параметров выражения объединения | dotnet_style_coalesce_expression |
Применение параметров условного выражения | dotnet_style_prefer_conditional_expression_over_assignment dotnet_style_prefer_conditional_expression_over_return |
Применение параметров имени кортежа | dotnet_style_explicit_tuple_names dotnet_style_prefer_inferred_tuple_names |
Применение параметров имен членов анонимного типа | dotnet_style_prefer_inferred_anonymous_type_member_names |
Применение параметров проверки null | dotnet_style_prefer_is_null_check_over_reference_equality_method |
Применение параметров распространения NULL | dotnet_style_null_propagation |
Применение параметров var | IDE0007-IDE0008 |
Добавление обязательных фигурных скобок для операторов однострочного элемента управления | csharp_prefer_braces |
Применить настройки тела выражения или блока | Элементы, воплощающие выражение |
Применить настройки встроенных выходных переменных | csharp_style_inlined_variable_declaration |
Применение параметров сопоставления шаблонов | Параметры сопоставления шаблонов |
Применение параметров вызова условного делегата | csharp_style_conditional_delegate_call |
Применение параметров статической локальной функции | csharp_prefer_static_local_function |
Применение параметров деконструккции | csharp_style_deconstructed_variable_declaration |
Применение параметров по умолчанию (T) | csharp_prefer_simple_default_expression |
Применение параметров new() | csharp_style_implicit_object_creation_when_type_is_apparent |
Применение параметров диапазона | csharp_style_prefer_range_operator |
Применение локальных параметров анонимной функции | csharp_style_pattern_local_over_anonymous_function |
Применение параметров NULL | Параметры проверки NULL |
Применение параметров инструкции using | csharp_prefer_simple_using_statement |
Применение параметров выражения throw | csharp_style_throw_expression |
Если вы хотите, чтобы параметры стиля кода применялись при каждом сохранении файла, перейдите в> раздел«Параметры очистки кода«> и выберите «Выполнить профиль очистки кода» при сохранении.
Если вы хотите применять параметры стиля кода при каждом сохранении файла, вам может подойти расширение для очистки кода при сохранении.
JS-CSS-HTML Formatter
lonefy
VS Code JS, CSS, HTML Formatting
This extension wraps js-beautify to format your JS, CSS, HTML, JSON file.
###To format Javascript,CSS and HTML after vscode v0.10.10
Edit the file as your needs. This extension uses js-beautify internally, so you can edit the parameters which js-beautify can use.
Restart vscode [!Important]
License
##Changes Log: ###0.2.3 31 Mar 2017
###0.2.2 23 Nov 2016
###0.2.0 20 July 2016
###0.1.32 15 July 2016
###0.1.3 06 May 2016
Add a new field in config file onSave (default true);
Support JSON file.
###0.1.0 26 Mar 2016
##THANKS: rjmacarthy, zhaopengme, Arrow7000, bitwiseman
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.
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.
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.
question
How to automatic format code in Visual Studio
I remember I had an automatic code formating right after I pressed ctrl+s.
Now I don’t have that.
All I have is «Code Formatter» that makes a lot of commets which I don’t need and when I remove those comments with «Clear Comments» it will remove my personal commets also.
Will be super glad for help here.
Hi, @Elado
I have not heard from you for a couple of days. Please let me know if there is anything that I can help here.
Hi, I did ctrl+k, ctrl +d and that did help me.
I’m searching for one time two keys press, its more easy, fast and not confusing!
Thanks
Hi, @Elado
I updated my answer please check it
6 Answers
I have
Ctrl + K, Ctrl + F
to format the selected text
or
Ctrl+ K, + Ctrl + D for the document :
Thank you. I will try that with the menu picture you put.
Although I remember Ctrl k or ctrl d didn’t do nothing.
It can be changed, but Ctrl K on a selection, then Ctrl F, correctly formats the code for me
You should have a default Code Cleanup profile if you go to «Analyze > Code Cleanup > Configure Code Cleanup»
If you move «Format document» from «Available fixers» to «Included fixer» (if it’s not already) then press «Ok» and it should format your documents based on your preferences.
There are a few fixers I use that are quite handy (Sort usings/Remove unnecessary usings probably the most useful to me):
How to format file in Visual Studio Code (hotkeys)?
How to format file | project folder | all project files (using hot keys AND using menu) in Visual Studio Code?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you’re on Windows use Shift + Alt + F to make your code «pretty».
(This is similar to Ctrl + K + D in Visual Studio)
You will have to do this for each individual file though. I don’t know of a way to format all files at once.
Try with this hotkeys
Your question looks like you are looking for a way to format your entire code in VSCode. If this is the case, a VSCode extension like Prettier should meet the three requirements you’ve listed (file | project folder | all project files). Bear in mind though that formatting all project files is a bit unclear and you probably want to be specific about formatting all *.ts or all *.js files etc.
The below may be of help to you:
The one I found most useful is adding it as a git pre-commit hook for staged files.
I hope above points you in the right direction.
Code Formatter
Utkarsh Chauhan
Code Formatter
Format the class file and arrange fields, properties and methods as per StyleCop rules.
Features
Feature Format class
Members of the class are arranged in following order
Furthermore the members are also sorted by access modifiers as follows
How to use
After installation can execute format code command from two different place.
Option 1
Option 2
Option 3
Option 4
Settings
Settings for tool can be accessed from Visual Studio options screen as shown below.
General Settings
Type Layout
You can customize the layout of the class or interface by setting required layout under Type layout setting
Note: That the first time when this extension is installed, type layout will be blank. Hence first time user will have to configure the type layout, and you can also set type layout with the help of the default templates.
File Header
You can also choose to include class header by updating setting under File Header.
You can customize the file header format and you can use the available replacement to format the header.
You can also have the different file header template based on the solution or project also.
To have customized file header for a perticular solution, go to Solution and right click and go to «Code Formatter >> Add Header Setting File». And you can set perticular format in that setting file.
Same is applicable of project level file header as well.
Note: File template selection will first check for project header setting file, if not found then it will look for solution header setting file and if the file is not present then global header will be applied.
Download this extension from the VS Gallery
1. If you are installing it manually using VSIX file then make sure you uninstall the previous version anf then install the new version. Because if at the same time multiple version are installed of the same extension then extension will be disabled by Visual Studio.
2. It is advisable to install the extension from Tools > Extensions and Update option.
Format Code Action
Rohit Gohri
Format Code Action
Run eslint extension after the prettier extension in VS Code. Or the other way around, whatever way you want.
Installation
Or install from within VS Code: Launch VS Code Quick Open (Ctrl+P or cmd+P), paste the following command, and press enter.
Or on the command line:
Usage
Disable formatOnSave and use the source.formatDocument codeAction in whatever order you want with VS Code settings:
NOTE: This was first released with source.fixAll.format as the codeAction, that still works for legacy purposes.
This runs ‘Format Document’ with the default formatter (in this case prettier).
Or for specific lanuage only:
This would run prettier by default, but for javascript files would run prettier and then eslint. If you want to reverse the order then just reverse the array.
Format Modified (EXPERIMENTAL)
Alternatively you may want to format only the modified part of the file, in that case use source.formatModified :
This is experimentally supported right now, if you face any problems please report them at: https://github.com/rohit-gohri/vscode-format-code-action/issues/5
Motivation
I created this so I could use prettier and eslint together in the editor, in a specific order (eslint after prettier). Earlier prettier was setup to run on save and eslint as a codeAction with:
This would often lead to prettier being run after eslint and eslint errors still being present.
Since the March 2020 (v1.44) update, VS Code allows setting codeActionsOnSave as an array. This allows setting the order of the codeActions.
The extension uses the CodeActionProvider api to implement a simple code action that runs ‘Format Document’ on the current file. This allows us to disable formatOnSave and use it as a codeAction instead in a specific order with other extensions.
Basic Editing
Visual Studio Code is an editor first and foremost, and includes the features you need for highly productive source code editing. This topic takes you through the basics of the editor and helps you get moving with your code.
Keyboard shortcuts
Being able to keep your hands on the keyboard when writing code is crucial for high productivity. VS Code has a rich set of default keyboard shortcuts as well as allowing you to customize them.
Multiple selections (multi-cursor)
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.
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:
There’s also a menu item Use Ctrl+Click for Multi-Cursor in the Selection menu to quickly toggle this setting.
Shrink/expand selection
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.
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
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:
If something happens to go wrong with hot exit, all backups are stored in the following folders for standard install locations:
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.
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.
Advanced find and replace options
In addition to find and replace with plain text, the Find Widget also has three advanced search options:
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
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.
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
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
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
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:
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, and HTML. 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:
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:
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 // | // #endregion or // |
Markdown | ||
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 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
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?
Is there a format code shortcut for Visual Studio?
12 Answers 12
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Visual Studio with C# key bindings
To answer the specific question, in C# you are likely to be using the C# keyboard mapping scheme, which will use these hotkeys by default:
You can change these in menu Tools → Options → Environment → Keyboard (either by selecting a different «keyboard mapping scheme», or binding individual keys to the commands «Edit.FormatDocument» and «Edit.FormatSelection»).
If you have not chosen to use the C# keyboard mapping scheme, then you may find the key shortcuts are different. For example, if you are not using the C# bindings, the keys are likely to be:
Ctrl + K + D (Entire document)
Ctrl + K + F (Selection only)
(Please do not edit this answer to change the key bindings above to what your system has!)
Format code command for PHP/HTML in Visual Studio Code
Is it possible to get Visual Studio Code to format mixed HTML and PHP code on Windows Visual Studio Code version 0.7.1?
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Update 2021-07-21
The free version of Intelephense supports code formatting with the usual shortcuts ( Alt + Shift + F on Windows and Linux, ⌥⇧F on macOS). Visual Studio Code continues to lack built-in support for PHP code formatting and will direct you to the extension marketplace if you attempt to format PHP without an appropriate extension installed.
Original answer
Visual Studio Code has pretty awesome PHP support. What it lacks is covered by extensions. A quick search reveals at least three (1, 2, and 3) that claim to support PHP formatting.
They mostly seem to use the standard shortcut of Alt + Shift + F on Windows/Linux, with varying shortcuts on Mac. If you’re on Mac, give ⌥⇧F a try.
Auto format C# code In Visual Studio Code
This is the sample code output I need to achieve:
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I have found an option which makes it easier to format code while typing.
I applied the below settings in workspace settings:
This works fine for me.
Go to menu File → Preference → Settings.
Search for format
Select the options you would like:
Format on Paste
Close the Settings window.
You can also see it in your settings.json file:
Click on the keybindings.json link:
Enter the below binding for the Enter key. This binding will overwrite the defaults for current user.
Add macros to User Settings :
And the below key binding to keybindings.json :
Code formatters available on Visual Studio default as
If you again wish to do it when pressing Enter you need to set up your workspace preferences and then configure the key bindings:
It now formats the whole document if nothing is selected, and else it formats the selection.
Also there is the beautify.onSave, editor.formatOnSave option. Please try that too to make the code pretty.
Edit: This doesn’t actually work because this will suppress the regular Enter key behavior
To get this to work for me I had to install two extensions
Without the second extension I was getting the error visual studio code there is no formatter for ‘csharp’-files installed
I also made sure my Visual Studio Code was up to date (menu* → Help → Restart and Update or Check for Updates)
Then I added a custom key binding. menu File → Preferences → Keyboard Shortcuts → «For advanced customizations open and edit keybindings.json»:
I had to type in the word enter because the dialog to capture keys doesn’t acknowledge it.
Visual Studio code formatter
I’m using Visual Studio 2008 for doing work in C# and JavaScript (AJAXy stuff).
Is there a way to get VS to behave like the IDE that I miss?
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Go into Tools | Options | Text Editor and edit the language specific settings to you’re liking. Ctrl-K, Ctrl-D honors these settings, so you can make the code formatter working the way you want. There are a ton of options you can change (bracket positioning, spacing, indenting, etc.).
I use the great Resharper plugin to format my C# code. Lots of settings to change to format your code to your liking. Can even make one coding standard with Resharper to be used by all your programmers.
As for key bindings, can change those in your options.
Visual Studio Code doesn’t format C# code
I created a new file, set the C# language, and wrote some code. Then I pressed Ctrl + Shift + F (or F1 → Format Document). And got I the error
Sorry, but there is no formatter for ‘csharp’-files installed.
Also, I installed C# Extension, but it didn’t help. The Visual Studio Code version is 1.18.0.
18 Answers 18
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you have prettier as the default formatter as I do, you should do this:
Then click to «open settings (JSON)»:
This is where you should paste the below snippet.
This is my config:
For you to apply this configuration you need c# extension.
This works for me.
Note: If it is true then clear the checkbox and set it to true again. After that, you must restart Visual Studio Code.
Menu File → Preferences → Settings →
3/4/5 unity engine projects on mac
Browse the Visual Studio Code extension library, and make sure you’ve got the C# extension installed ms-dotnettools.csharp
Restart Visual Studio Code. It should now make code auto-format when you complete the line with a semicolon, or when you close the outer brace of a scope.
Note: this is a global setting for the editor, so it may enable auto-formatting for other languages and not just C#.
This was tested on Visual Studio Code version 1.43.1.
Automatically reformat Python code in Visual Studio
Visual Studio lets you quickly reformat code to match pre-configured formatting options.
Define formatting rules
You can set your formatting options through the menus Tools > Options > Text Editor > Python > Formatting and its nested tabs. Formatting options by default are set to match a superset of the PEP 8 style guide. The General tab determines when formatting is applied; settings for the other three tabs are described in this article.
You need to select Show all settings for these options to appear:
Python support in Visual Studio also adds the useful Fill Comment Paragraph command to the Edit > Advanced menu as described in a later section.
Apply format to selection or file
To format a selection:
To format the whole file:
Spacing examples
Spacing controls where spaces are inserted or removed around various language constructs. Each option has three possible values:
Examples for the various options are provided in the following tables:
Statement options
The Statements options control automatic rewriting of various statements into more Pythonic forms.
Option | Before formatting | After formatting |
---|---|---|
Place imported modules on new line | import sys, pickle | import sys import pickle |
Remove unnecessary semicolons | x = 42; | x = 42 |
Place multiple statements on new lines | x = 42; y = 100 | x = 42 y = 100 |
Wrapping options
Wrapping lets you set the Maximum comment width (default is 80). If the Wrap comments that are too wide option is set, Visual Studio reformats comments to not exceed that maximum width.
Format comment text
Edit > Advanced > Fill Comment Paragraph (Ctrl+E > P) reflows and formats comment text, combining short lines together and breaking up long ones.
Visual Studio Code formatting for «< >«
I’m on Ubuntu. C++ in Visual Studio Code automatically lints like
Instead I want to do :
How do I do that?
I’ve already installed the C/C++ extension from the marketplace.
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
base on @Chris Drew’s answer
If you want more:
I generally have my own way of formatting almost everything 🙂 so i prefer the most flexible way to achieve this. VS code is by far the most flexible editor as far as c++ formatting is concerned and also «easy».
This is what you should do to get custom formatting.
Here is my file for your reference.
The formatting you are interested in especially is «AfterControlStatement: false»
Using MacOS for example, an ideal method of configuring clang-format for VS Code is to first install clang-format with Homebrew:
Then, use it to export the full style settings to
Then, perform the following in VS Code:
This sets the formatter to the clang-formatter installed with Homebrew, which will automatically pull your style settings from the
/.clang-format file you just created. This way, you can change every parameter in the style as desired and not just a subset of these.
Is there a format code shortcut for Visual Studio?
12 Answers 12
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Visual Studio with C# key bindings
To answer the specific question, in C# you are likely to be using the C# keyboard mapping scheme, which will use these hotkeys by default:
You can change these in menu Tools → Options → Environment → Keyboard (either by selecting a different «keyboard mapping scheme», or binding individual keys to the commands «Edit.FormatDocument» and «Edit.FormatSelection»).
If you have not chosen to use the C# keyboard mapping scheme, then you may find the key shortcuts are different. For example, if you are not using the C# bindings, the keys are likely to be:
Ctrl + K + D (Entire document)
Ctrl + K + F (Selection only)
(Please do not edit this answer to change the key bindings above to what your system has!)
Visual Studio Code Tips and Tricks
«Tips and Tricks» lets you jump right in and learn how to be productive with Visual Studio Code. You’ll become familiar with its powerful editing, code intelligence, and source code control features and learn useful keyboard shortcuts. This topic goes pretty fast and provides a broad overview, so be sure to look at the other in-depth topics in Getting Started and the User Guide to learn more.
If you don’t have Visual Studio Code installed, go to the Download page. You can find platform specific setup instructions at Running VS Code on Linux, macOS, and Windows.
Prefer a video? You can watch a recent Microsoft Build talk Visual Studio Code tips and tricks, which describes 20 tips and tricks for working productively with VS Code.
Basics
Getting started
The best way of exploring VS Code hands-on is to open the Get Started page. You will get an overview of VS Code’s customizations and features. Help > Get Started.
Pick a Walkthrough for a self-guided tour through the setup steps, features, and deeper customizations that VS Code offers. As you discover and learn, the walkthroughs track your progress.
If you are looking to improve your code editing skills open the Interactive Editor Playground. Try out VS Code’s code editing features, like multi-cursor editing, IntelliSense, Snippets, Emmet, and many more. Help > Editor Playground.
Command Palette
Access all available commands based on your current context.
Keyboard Shortcut: ⇧⌘P (Windows, Linux Ctrl+Shift+P )
Default keyboard shortcuts
All of the commands are in the Command Palette with the associated key binding (if it exists). If you forget a keyboard shortcut, use the Command Palette to help you out.
Keyboard reference sheets
Download the keyboard shortcut reference sheet for your platform (macOS, Windows, Linux).
Quick Open
Quickly open files.
Keyboard Shortcut: ⌘P (Windows, Linux Ctrl+P )
Typing commands such as edt and term followed by a space will bring up dropdown lists.
Navigate between recently opened files
Repeat the Quick Open keyboard shortcut to cycle quickly between recently opened files.
Open multiple files from Quick Open
You can open multiple files from Quick Open by pressing the Right arrow key. This will open the currently selected file in the background and you can continue selecting files from Quick Open.
Navigate between recently opened folders and workspaces
Keyboard Shortcut: ⌃R (Windows, Linux Ctrl+R )
Displays a Quick Pick dropdown with the list from File > Open Recent with recently opened folders and workspaces followed by files.
Command line
VS Code has a powerful command line interface (CLI) which allows you to customize how the editor is launched to support various scenarios.
Make sure the VS Code binary is on your path so you can simply type ‘code’ to launch VS Code. See the platform specific setup topics if VS Code is added to your environment path during installation (Running VS Code on Linux, macOS, Windows).
.vscode folder
Status Bar
Errors and warnings
Keyboard Shortcut: ⇧⌘M (Windows, Linux Ctrl+Shift+M )
Quickly jump to errors and warnings in the project.
Cycle through errors with F8 or ⇧F8 (Windows, Linux Shift+F8 )
You can filter problems either by type (‘errors’, ‘warnings’) or text matching.
Change language mode
Keyboard Shortcut: ⌘K M (Windows, Linux Ctrl+K M )
If you want to persist the new language mode for that file type, you can use the Configure File Association for command to associate the current file extension with an installed language.
Customization
There are many things you can do to customize VS Code.
Change your theme
Keyboard Shortcut: ⌘K ⌘T (Windows, Linux Ctrl+K Ctrl+T )
You can install more themes from the VS Code extension Marketplace.
Additionally, you can install and change your File Icon themes.
Keymaps
Are you used to keyboard shortcuts from another editor? You can install a Keymap extension that brings the keyboard shortcuts from your favorite editor to VS Code. Go to Preferences > Migrate Keyboard Shortcuts from. to see the current list on the Marketplace. Some of the more popular ones:
Customize your keyboard shortcuts
Keyboard Shortcut: ⌘K ⌘S (Windows, Linux Ctrl+K Ctrl+S )
You can search for shortcuts and add your own keybindings to the keybindings.json file.
Tune your settings
By default VS Code shows the Settings editor, you can find settings listed below in a search bar, but you can still edit the underlying settings.json file by using the Open Settings (JSON) command or by changing your default settings editor with the workbench.settings.editor setting.
Open User Settings settings.json
Keyboard Shortcut: ⌘, (Windows, Linux Ctrl+, )
Change the font size of various UI elements
Change the zoom level
Tip: You will need to have a font installed that supports font ligatures. FiraCode is a popular font on the VS Code team.
You can also toggle Auto Save from the top-level menu with the File > Auto Save.
Format on paste
Change the size of Tab characters
Whitespace characters are rendered by default in text selection.
Ignore files / folders
Removes these files / folders from your editor window.
Remove these files / folders from search results.
Language specific settings
You can scope the settings that you only want for specific languages by the language identifier. You can find a list of commonly used language IDs in the Language Identifiers reference.
Tip: You can also create language specific settings with the Configure Language Specific Settings command.
Add JSON validation
Enabled by default for many file types. Create your own schema and validation in settings.json
or for a schema defined in your workspace
or a custom schema
See more in the JSON documentation.
Extensions
Keyboard Shortcut: ⇧⌘X (Windows, Linux Ctrl+Shift+X )
Find extensions
Install extensions
In the Extensions view, you can search via the search bar or click the More Actions (. ) button to filter and sort by install count.
Extension recommendations
In the Extensions view, click Show Recommended Extensions in the More Actions (. ) button menu.
Creating my own extension
Are you interested in creating your own extension? You can learn how to do this in the Extension API documentation, specifically check out the documentation on contribution points.
Files and folders
Integrated Terminal
Keyboard Shortcut: ⌃` (Windows, Linux Ctrl+` )
Toggle Sidebar
Keyboard Shortcut: ⌘B (Windows, Linux Ctrl+B )
Toggle Panel
Keyboard Shortcut: ⌘J (Windows, Linux Ctrl+J )
Zen mode
Keyboard Shortcut: ⌘K Z (Windows, Linux Ctrl+K Z )
Enter distraction free Zen mode.
Press Esc twice to exit Zen Mode.
Side by side editing
Keyboard Shortcut: ⌘\ (Windows, Linux Ctrl+\ )
You can also drag and drop editors to create new editor groups and move editors between groups.
Switch between editors
Move to Explorer window
Keyboard Shortcut: ⇧⌘E (Windows, Linux Ctrl+Shift+E )
Create or open a file
Keyboard Shortcut: Ctrl+click ( Cmd+click on macOS)
Close the currently opened folder
Keyboard Shortcut: ⌘K F (Windows, Linux Ctrl+K F )
Navigation history
Navigate entire history: ⌃Tab (Windows, Linux Ctrl+Tab )
File associations
Create language associations for files that aren’t detected correctly. For example, many configuration files with custom file extensions are actually JSON.
Preventing dirty writes
VS Code will show you an error message when you try to save a file that cannot be saved because it has changed on disk. VS Code blocks saving the file to prevent overwriting changes that have been made outside of the editor.
In order to resolve the save conflict, click the Compare action in the error message to open a diff editor that will show you the contents of the file on disk (to the left) compared to the contents in VS Code (on the right):
Use the actions in the editor toolbar to resolve the save conflict. You can either Accept your changes and thereby overwriting any changes on disk, or Revert to the version on disk. Reverting means that your changes will be lost.
Note: The file will remain dirty and cannot be saved until you pick one of the two actions to resolve the conflict.
Editing hacks
Here is a selection of common features for editing code. If the keyboard shortcuts aren’t comfortable for you, consider installing a keymap extension for your old editor.
Multi cursor selection
To add cursors at arbitrary positions, select a position with your mouse and use Alt+Click ( Option+Click on macOS).
To set cursors above or below the current position use:
If you do not want to add all occurrences of the current selection, you can use ⌘D (Windows, Linux Ctrl+D ) instead. This only selects the next occurrence after the one you selected so you can add selections one by one.
Column (box) selection
You can select blocks of text by holding Shift+Alt ( Shift+Option on macOS) while you drag your mouse. A separate cursor will be added to the end of each selected line.
You can also use keyboard shortcuts to trigger column selection.
Vertical rulers
You can 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.
Fast scrolling
Pressing the Alt key enables fast scrolling in the editor and Explorers. By default, fast scrolling uses a 5X speed multiplier but you can control the multiplier with the Editor: Fast Scroll Sensitivity ( editor.fastScrollSensitivity ) setting.
Copy line up / down
The commands Copy Line Up/Down are unbound on Linux because the VS Code default keybindings would conflict with Ubuntu keybindings, see Issue #509. You can still set the commands editor.action.copyLinesUpAction and editor.action.copyLinesDownAction to your own preferred keyboard shortcuts.
Move line up and down
Keyboard Shortcut: ⌥↑ (Windows, Linux Alt+Up ) or ⌥↓ (Windows, Linux Alt+Down )
Shrink / expand selection
Keyboard Shortcut: ⌃⇧⌘← (Windows, Linux Shift+Alt+Left ) or ⌃⇧⌘→ (Windows, Linux Shift+Alt+Right )
You can learn more in the Basic Editing documentation.
Go to Symbol in File
Keyboard Shortcut: ⇧⌘O (Windows, Linux Ctrl+Shift+O )
Go to Symbol in Workspace
Keyboard Shortcut: ⌘T (Windows, Linux Ctrl+T )
Outline view
The Outline view in the File Explorer (default collapsed at the bottom) shows you the symbols of the currently open file.
You can sort by symbol name, category, and position in the file and allows quick navigation to symbol locations.
Navigate to a specific line
Keyboard Shortcut: ⌃G (Windows, Linux Ctrl+G )
Undo cursor position
Keyboard Shortcut: ⌘U (Windows, Linux Ctrl+U )
Trim trailing whitespace
Keyboard Shortcut: ⌘K ⌘X (Windows, Linux Ctrl+K Ctrl+X )
Transform text commands
You can change selected text to uppercase, lowercase, and title case with the Transform commands from the Command Palette.
Code formatting
Currently selected source code: ⌘K ⌘F (Windows, Linux Ctrl+K Ctrl+F )
Code folding
Keyboard Shortcut: ⌥⌘[ (Windows, Linux Ctrl+Shift+[ ) and ⌥⌘] (Windows, Linux Ctrl+Shift+] )
You can also fold/unfold all regions in the editor with Fold All ( ⌘K ⌘0 (Windows, Linux Ctrl+K Ctrl+0 ) ) and Unfold All ( ⌘K ⌘J (Windows, Linux Ctrl+K Ctrl+J ) ).
You can fold all block comments with Fold All Block Comments ( ⌘K ⌘/ (Windows, Linux Ctrl+K Ctrl+/ ) ).
Select current line
Keyboard Shortcut: ⌘L (Windows, Linux Ctrl+L )
Navigate to beginning and end of file
Keyboard Shortcut: ⌘↑ (Windows, Linux Ctrl+Home ) and ⌘↓ (Windows, Linux Ctrl+End )
Open Markdown preview
In a Markdown file, use
Keyboard Shortcut: ⇧⌘V (Windows, Linux Ctrl+Shift+V )
Side by side Markdown edit and preview
In a Markdown file, use
Keyboard Shortcut: ⌘K V (Windows, Linux Ctrl+K V )
The preview and editor will synchronize with your scrolling in either view.
IntelliSense
⌃Space (Windows, Linux Ctrl+Space ) to trigger the Suggestions widget.
You can view available methods, parameter hints, short documentation, etc.
Go to Definition
You can also see the type definition if you press Ctrl ( Cmd on macOS) when you are hovering over the type.
Go to References
Find All References view
Select a symbol then type ⇧⌥F12 (Windows, Linux Shift+Alt+F12 ) to open the References view showing all your file’s symbols in a dedicated view.
Rename Symbol
Search and modify
.eslintrc.json
Install the ESLint extension. Configure your linter however you’d like. Consult the ESLint specification for details on its linting rules and options.
Here is configuration to use ES6.
package.json
See IntelliSense for your package.json file.
Emmet syntax
Snippets
Create custom snippets
File > Preferences > User Snippets (Code > Preferences > User Snippets on macOS), select the language, and create a snippet.
Git integration
Keyboard Shortcut: ⌃⇧G (Windows, Linux Ctrl+Shift+G )
Git integration comes with VS Code «out-of-the-box». You can install other SCM providers from the Extension Marketplace. This section describes the Git integration but much of the UI and gestures are shared by other SCM providers.
Diffs
From the Source Control view, select a file to open the diff.
Alternatively, click the Open Changes button in the top right corner to diff the current open file.
Views
The default view for diffs is the side by side view.
Toggle inline view by clicking the More Actions (. ) button in the top right and selecting Toggle Inline View.
Review pane
Edit pending changes
You can make edits directly in the pending changes of the diff view.
Branches
Easily switch between Git branches via the Status Bar.
Staging
Stage file changes
Hover over the number of files and click the plus button.
Click the minus button to unstage changes.
Stage selected
Stage a portion of a file by selecting that file (using the arrows) and then choosing Stage Selected Ranges from the Command Palette.
Undo last commit
Click the (. ) button and then select Undo Last Commit to undo the previous commit. The changes are added to the Staged Changes section.
See Git output
VS Code makes it easy to see what Git commands are actually running. This is helpful when learning Git or debugging a difficult source control issue.
Gutter indicators
View diff decorations in editor. See documentation for more details.
Resolve merge conflicts
During a merge, go to the Source Control view ( ⌃⇧G (Windows, Linux Ctrl+Shift+G ) ) and make changes in the diff view.
You can resolve merge conflicts with the inline CodeLens which lets you Accept Current Change, Accept Incoming Change, Accept Both Changes, and Compare Changes.
Set VS Code as default merge tool
Set VS Code as default diff tool
Debugging
Configure debugger
From the Run and Debug view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ), select create a launch.json file, which will prompt you to select the environment that matches your project (Node.js, Python, C++, etc). This will generate a launch.json file. Node.js support is built-in and other environments require installing the appropriate language extensions. See the debugging documentation for more details.
Breakpoints and stepping through
Place breakpoints next to the line number. Navigate forward with the Debug widget.
Data inspection
Inspect variables in the Run panels and in the console.
Logpoints
Logpoints act much like breakpoints but instead of halting the debugger when they are hit, they log a message to the console. Logpoints are especially useful for injecting logging while debugging production servers that cannot be modified or paused.
Add a logpoint with the Add Logpoint command in the left editor gutter and it will be displayed as a «diamond» shaped icon. Log messages are plain text but can include expressions to be evaluated within curly braces (‘<>‘).
Task runner
Auto detect tasks
Select Terminal from the top-level menu, run the command Configure Tasks, then select the type of task you’d like to run. This will generate a tasks.json file with content like the following. See the Tasks documentation for more details.
There are occasionally issues with auto generation. Check out the documentation for getting things to work properly.
Run tasks from the Terminal menu
Select Terminal from the top-level menu, run the command Run Task, and select the task you want to run. Terminate the running task by running the command Terminate Task
Define keyboard shortcuts for tasks
For example, to bind Ctrl+H to the Run tests task, add the following:
Run npm scripts as tasks from the Explorer
Portable mode
VS Code has a Portable mode which lets you keep settings and data in the same location as your installation, for example, on a USB drive.
Insiders builds
The Visual Studio Code team uses the Insiders version to test the latest features and bug fixes of VS Code. You can also use the Insiders version by downloading it here.
Visual Studio Code formatting for «< >«
I’m on Ubuntu. C++ in Visual Studio Code automatically lints like
Instead I want to do :
How do I do that?
I’ve already installed the C/C++ extension from the marketplace.
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
base on @Chris Drew’s answer
If you want more:
I generally have my own way of formatting almost everything 🙂 so i prefer the most flexible way to achieve this. VS code is by far the most flexible editor as far as c++ formatting is concerned and also «easy».
This is what you should do to get custom formatting.
Here is my file for your reference.
The formatting you are interested in especially is «AfterControlStatement: false»
Using MacOS for example, an ideal method of configuring clang-format for VS Code is to first install clang-format with Homebrew:
Then, use it to export the full style settings to
Then, perform the following in VS Code:
This sets the formatter to the clang-formatter installed with Homebrew, which will automatically pull your style settings from the
/.clang-format file you just created. This way, you can change every parameter in the style as desired and not just a subset of these.
Format code command for PHP/HTML in Visual Studio Code
Is it possible to get Visual Studio Code to format mixed HTML and PHP code on Windows Visual Studio Code version 0.7.1?
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Update 2021-07-21
The free version of Intelephense supports code formatting with the usual shortcuts ( Alt + Shift + F on Windows and Linux, ⌥⇧F on macOS). Visual Studio Code continues to lack built-in support for PHP code formatting and will direct you to the extension marketplace if you attempt to format PHP without an appropriate extension installed.
Original answer
Visual Studio Code has pretty awesome PHP support. What it lacks is covered by extensions. A quick search reveals at least three (1, 2, and 3) that claim to support PHP formatting.
They mostly seem to use the standard shortcut of Alt + Shift + F on Windows/Linux, with varying shortcuts on Mac. If you’re on Mac, give ⌥⇧F a try.
Editing Python in Visual Studio Code
Visual Studio Code is a powerful editing tool for Python source code. The editor includes various features to help you be productive when writing code. For more information about editing in Visual Studio Code, see Basic Editing and Code Navigation.
In this overview, we will describe the specific editing features provided by the Python extension, including steps on how to customize these features via user and workspace settings.
Autocomplete and IntelliSense
IntelliSense is a general term for code editing features that relate to code completion. Take a moment to look at the example below. When print is typed, notice how IntelliSense populates auto-completion options. The user is also given a list of options when they begin to type the variable named, greeting.
Autocomplete and IntelliSense are provided for all files within the current working folder. They’re also available for Python packages that are installed in standard locations.
Customize IntelliSense behavior
To customize the behavior of the analysis engine, see the Python extension code analysis settings and autocomplete settings.
You can also customize the general behavior of autocomplete and IntelliSense, even to disable these VS Code features entirely. See Customizing IntelliSense.
Tip: Check out the IntelliCode extension for VS Code (preview). IntelliCode provides a set of AI-assisted capabilities for IntelliSense in Python, such as inferring the most relevant auto-completions based on the current code context. For more information, see the IntelliCode for VS Code FAQ.
Enable IntelliSense for custom package locations
To enable IntelliSense for packages that are installed in other, non-standard locations, add those locations to the python.autoComplete.extraPaths collection in the settings file (the default collection is empty). For example, you might have installed Google App Engine installed in custom locations, specified in app.yaml if you use Flask. In this case, you’d specify those locations as follows:
Windows:
macOS/Linux:
For more on IntelliSense generally, see IntelliSense.
Troubleshooting IntelliSense
If autocomplete and IntelliSense aren’t working for a custom module, check the following causes:
Cause | Solution |
---|---|
The path to the python interpreter is incorrect | Make sure you selected a valid interpreter path by running the Python: Select Interpreter command (see Environments). |
The custom module is located in a non-standard location (not installed using pip). | Add the location to the python.autoComplete.extraPaths setting and restart VS Code. |
Navigation
While editing, you can right-click different identifiers to take advantage of several convenient commands
Go to Definition ( F12 ) jumps from your code into the code that defines an object. This command is helpful when you’re working with libraries.
Go to Declaration jumps to the point at which the variable or other object is declared in your code.
Peek Declaration is similar, but displays the declaration directly in the editor. Again, use Escape or the x in the upper right corner to close the Peek window.
Quick Fixes
The add imports Quick Fix allows you to quickly complete import statements. First, begin by typing a package name within the editor. You will notice a Code Action is available to automatically complete the line of source code (as long as you have the module installed within the environment). Hover over the text (marked with a squiggle) and then select the Code Action light bulb when it appears. You can then select from a list of potential imports. Note: The functionality in the below examples is provided by the Pylance language server.
The import suggestions list is ordered with import statements for packages (or modules) at the top. It will also include statements for more modules and/or members (classes, objects, etc.) from specified packages.
Run Selection/Line in Terminal (REPL)
The Python: Run Selection/Line in Python Terminal command ( Shift+Enter ) is a simple way to take whatever code is selected, or the code on the current line if there is no selection, and run it in the Python Terminal. An identical Run Selection/Line in Python Terminal command is also available on the context menu for a selection in the editor.
VS Code automatically removes indents based on the first non-empty line of the selection, shifting all other lines left when needed.
Source code that runs in the terminal/REPL is cumulative until the current instance of the terminal is closed.
On first use of the Python: Run Selection/Line in Python Terminal command, VS Code may send the text to the REPL before that environment is ready, in which case the selection or line isn’t run. If you come across this behavior, try the command again when the REPL has finished loading.
Formatting
Formatting makes code easier to read by human beings. It applies specific rules and conventions for line spacing, indents, spacing around operators, and so on. You can view an example on the autopep8 page. Keep in mind, formatting doesn’t affect the functionality of the code itself.
Linting helps to prevent errors by analyzing code for common syntactical, stylistic, and functional errors and unconventional programming practices. Although there is a little overlap between formatting and linting, the two capabilities are complementary.
The Python extension supports source code formatting using either autopep8 (the default), black, or yapf.
General formatting settings
Setting (python.formatting.) | Default value | Description |
---|---|---|
provider | «autopep8» | Specifies the formatter to use, either «autopep8», «yapf», or «black». |
Formatter-specific settings
The following settings apply to the individual formatters. The Python extension looks for the formatter in the selected interpreter. To use a formatter in another location, specify that location in the appropriate custom path setting. The pip install commands may require elevation.
Note: By default, the Black formatter can’t be installed when a Python 2 environment is active. Attempting to do so may display the message «Formatter black is not installed. Install?». If you try to install Black in response, another message appears saying «Could not find a version that satisfies the requirement black’ No matching distribution found for black.»
To work around this issue and use the Black formatter with Python 2, first install Black in a Python 3 environment. Then set the python.formatting.blackPath setting to that install location.
When using custom arguments, each top-level element of an argument string that’s separated by space on the command line must be a separate item in the args list. For example:
In the second example, the top-level element
Troubleshooting formatting
If formatting fails, check the following possible causes:
Refactoring
The Python extension adds the following refactoring functionalities: Extract Variable, Extract Method, Rename Module, and Sort Imports.
Extract Variable
Extracts all similar occurrences of the selected text within the current scope, and replaces it with a new variable.
You can invoke this command by selecting the line of code you wish to extract as a variable. Then select the light-bulb that is displayed next to it.
Extract Method
Extracts all similar occurrences of the selected expression or block within the current scope, and replaces it with a method call.
You can invoke this command by selecting the lines of code you wish to extract as a method. Then select the light-bulb that is displayed next to it.
Rename Module
After a Python file/module is renamed, Pylance can find all instances that may need to be updated and provide you with a preview of all the changes.
To customize which references need to be updated, you can toggle the checkboxes at the line or from the file level in Refactor Preview. Once you’ve made your selections, you can select Apply Refactoring or Discard Refactoring.
Sort Imports
Sort Imports uses the isort package to consolidate specific imports from the same module into a single import statement and to organize import statements in alphabetical order.
Custom arguments to isort are specified in the python.sortImports.args setting, where each top-level element, as separated by spaces on the command line, is a separate item in the array:
To use a custom isort script, use the python.sortImports.path setting to specify the path.
Note: For those migrating from isort4 to isort5, some CLI flags and config options have changed, refer to the project’s isort5 upgrade guide.
How can I modify the code formatting for C++ in Visual Studio Code?
So far after installing the C++ extension tool, I can use Ctrl + K + F to auto-format my C++ code. However, I would like to make some modification, for example I would like to force the pointer alignment to be near the type, instead of next to the variable name, such as this rule:
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
After some experiments, the simple solution is to add this line in the User Settings (settings.json):
However, this settings allow me to keep my previous settings without breaking my function line:
Using «BasedOnStyle: Visual Studio» such as this line:
doesn’t work. It is may be a bug. I used Visual Studio Code version 1.26.1.
Key Bindings for Visual Studio Code
Visual Studio Code lets you perform most tasks directly from the keyboard. This page lists out the default bindings (keyboard shortcuts) and describes how you can update them.
Note: If you visit this page on a Mac, you will see the key bindings for the Mac. If you visit using Windows or Linux, you will see the keys for that platform. If you need the key bindings for another platform, hover your mouse over the key you are interested in.
Keyboard Shortcuts editor
Visual Studio Code provides a rich and easy keyboard shortcuts editing experience using Keyboard Shortcuts editor. It lists all available commands with and without keybindings and you can easily change / remove / reset their keybindings using the available actions. It also has a search box on the top that helps you in finding commands or keybindings. You can open this editor by going to the menu under File > Preferences > Keyboard Shortcuts. (Code > Preferences > Keyboard Shortcuts on macOS)
Most importantly, you can see keybindings according to your keyboard layout. For example, key binding Cmd+\ in US keyboard layout will be shown as Ctrl+Shift+Alt+Cmd+7 when layout is changed to German. The dialog to enter key binding will assign the correct and desired key binding as per your keyboard layout.
For doing more advanced keyboard shortcut customization, read Advanced Customization.
Keymap extensions
Keyboard shortcuts are vital to productivity and changing keyboarding habits can be tough. To help with this, File > Preferences > Migrate Keyboard Shortcuts from. shows you a list of popular keymap extensions. These extensions modify the VS Code shortcuts to match those of other editors so you don’t need to learn new keyboard shortcuts. There is also a Keymaps category of extensions in the Marketplace.
Tip: Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.
Keyboard Shortcuts Reference
We also have a printable version of these keyboard shortcuts. Help > Keyboard Shortcut Reference displays a condensed PDF version suitable for printing as an easy reference.
Below are links to the three platform-specific versions (US English keyboard):
Detecting keybinding conflicts
If you have many extensions installed or you have customized your keyboard shortcuts, you can sometimes have keybinding conflicts where the same keyboard shortcut is mapped to several commands. This can result in confusing behavior, especially if different keybindings are going in and out of scope as you move around the editor.
The Keyboard Shortcuts editor has a context menu command Show Same Keybindings, which will filter the keybindings based on a keyboard shortcut to display conflicts.
Pick a command with the keybinding you think is overloaded and you can see if multiple commands are defined, the source of the keybindings and when they are active.
Troubleshooting keybindings
To troubleshoot keybindings problems, you can execute the command Developer: Toggle Keyboard Shortcuts Troubleshooting. This will activate logging of dispatched keyboard shortcuts and will open an output panel with the corresponding log file.
You can then press your desired keybinding and check what keyboard shortcut VS Code detects and what command is invoked.
For example, when pressing cmd+/ in a code editor on macOS, the logging output would be:
Viewing modified keybindings
You can view any user modified keyboard shortcuts in VS Code in the Keyboard Shortcuts editor with the Show User Keybindings command in the More Actions (. ) menu. This applies the @source:user filter to the Keyboard Shortcuts editor (Source is ‘User’).
Advanced customization
All keyboard shortcuts in VS Code can be customized via the keybindings.json file.
You can also open the keybindings.json file from the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) with the Preferences: Open Keyboard Shortcuts (JSON) command.
Keyboard rules
Each rule consists of:
When a key is pressed:
The additional keybindings.json rules are appended at runtime to the bottom of the default rules, thus allowing them to overwrite the default rules. The keybindings.json file is watched by VS Code so editing it while VS Code is running will update the rules at runtime.
The keyboard shortcuts dispatching is done by analyzing a list of rules that are expressed in JSON. Here are some examples:
Accepted keys
The key is made up of modifiers and the key itself.
The following modifiers are accepted:
The following keys are accepted:
Command arguments
You can invoke a command with arguments. This is useful if you often perform the same operation on a specific file or folder. You can add a custom keyboard shortcut to do exactly what you want.
The following is an example overriding the Enter key to print some text:
The type command will receive <"text": "Hello World">as its first argument and add «Hello World» to the file instead of producing the default command.
For more information on commands that take arguments, refer to Built-in Commands.
Removing a specific key binding rule
Here is an example:
Keyboard layouts
Note: This section relates only to key bindings, not to typing in the editor.
The keys above are string representations for virtual keys and do not necessarily relate to the produced character when they are pressed. More precisely:
Different keyboard layouts usually reposition the above virtual keys or change the characters produced when they are pressed. When using a different keyboard layout than the standard US, Visual Studio Code does the following:
All the key bindings are rendered in the UI using the current system’s keyboard layout. For example, Split Editor when using a French (France) keyboard layout is now rendered as Ctrl+* :
Note: On Linux, Visual Studio Code detects your current keyboard layout on start-up and then caches this information. For a good experience, we recommend restarting VS Code if you change your keyboard layout.
Keyboard layout-independent bindings
Using scan codes, it is possible to define keybindings which do not change with the change of the keyboard layout. For example:
Accepted scan codes:
when clause contexts
VS Code gives you fine control over when your key bindings are enabled through the optional when clause. If your key binding doesn’t have a when clause, the key binding is globally available at all times. A when clause evaluates to either Boolean true or false for enabling key bindings.
You can also view a keybinding’s when clause directly in the Default Keybindings JSON (Preferences: Open Default Keyboard Shortcuts (JSON)):
Conditional operators
For when clause conditional expressions, the following conditional operators are useful for keybindings:
You can find the full list of when clause conditional operators in the when clause contexts reference.
Available contexts
You can find some of the available when clause contexts in the when clause context reference.
The list there isn’t exhaustive and you can find other when clause contexts by searching and filtering in the Keyboard Shortcuts editor (Preferences: Open Keyboard Shortcuts ) or reviewing the Default Keybindings JSON file (Preferences: Open Default Keyboard Shortcuts (JSON)).
Custom keybindings for refactorings
The editor.action.codeAction command lets you configure keybindings for specific Refactorings (Code Actions). For example, the keybinding below triggers the Extract function refactoring Code Actions:
This is covered in depth in the Refactoring topic where you can learn about different kinds of Code Actions and how to prioritize them in the case of multiple possible refactorings.
Default Keyboard Shortcuts
You can view all default keyboard shortcuts in VS Code in the Keyboard Shortcuts editor with the Show Default Keybindings command in the More Actions (. ) menu. This applies the @source:default filter to the Keyboard Shortcuts editor (Source is ‘Default’).
You can view the default keyboard shortcuts as a JSON file using the command Preferences: Open Default Keyboard Shortcuts (JSON).
Some commands included below do not have default keyboard shortcuts and so are displayed as unassigned but you can assign your own keybindings.
Basic Editing
Rich Languages Editing
Navigation
Editor/Window Management
Command | Key | Command id |
---|---|---|
New Window | ⇧⌘N (Windows, Linux Ctrl+Shift+N ) | workbench.action.newWindow |
Close Window | ⌘W (Windows, Linux Alt+F4 ) | workbench.action.closeWindow |
Close Editor | ⌘W (Windows, Linux Ctrl+W ) | workbench.action.closeActiveEditor |
Close Folder | ⌘K F (Windows, Linux Ctrl+K F ) | workbench.action.closeFolder |
Cycle Between Editor Groups | workbench.action.navigateEditorGroups | |
Split Editor | ⌘\ (Windows, Linux Ctrl+\ ) | workbench.action.splitEditor |
Focus into First Editor Group | ⌘1 (Windows, Linux Ctrl+1 ) | workbench.action.focusFirstEditorGroup |
Focus into Second Editor Group | ⌘2 (Windows, Linux Ctrl+2 ) | workbench.action.focusSecondEditorGroup |
Focus into Third Editor Group | ⌘3 (Windows, Linux Ctrl+3 ) | workbench.action.focusThirdEditorGroup |
Focus into Editor Group on the Left | workbench.action.focusPreviousGroup | |
Focus into Editor Group on the Right | workbench.action.focusNextGroup | |
Move Editor Left | ⌘K ⇧⌘← (Windows, Linux Ctrl+Shift+PageUp ) | workbench.action.moveEditorLeftInGroup |
Move Editor Right | ⌘K ⇧⌘→ (Windows, Linux Ctrl+Shift+PageDown ) | workbench.action.moveEditorRightInGroup |
Move Active Editor Group Left | ⌘K ← (Windows, Linux Ctrl+K Left ) | workbench.action.moveActiveEditorGroupLeft |
Move Active Editor Group Right | ⌘K → (Windows, Linux Ctrl+K Right ) | workbench.action.moveActiveEditorGroupRight |
Move Editor into Next Group | ⌃⌘→ (Windows, Linux Ctrl+Alt+Right ) | workbench.action.moveEditorToNextGroup |
Move Editor into Previous Group | ⌃⌘← (Windows, Linux Ctrl+Alt+Left ) | workbench.action.moveEditorToPreviousGroup |
File Management
Display
Search
Command | Key | Command id |
---|---|---|
Show Search | ⇧⌘F (Windows, Linux Ctrl+Shift+F ) | workbench.view.search |
Replace in Files | ⇧⌘H (Windows, Linux Ctrl+Shift+H ) | workbench.action.replaceInFiles |
Toggle Match Case | ⌥⌘C (Windows, Linux Alt+C ) | toggleSearchCaseSensitive |
Toggle Match Whole Word | ⌥⌘W (Windows, Linux Alt+W ) | toggleSearchWholeWord |
Toggle Use Regular Expression | ⌥⌘R (Windows, Linux Alt+R ) | toggleSearchRegex |
Toggle Search Details | ⇧⌘J (Windows, Linux Ctrl+Shift+J ) | workbench.action.search.toggleQueryDetails |
Focus Next Search Result | F4 | search.action.focusNextSearchResult |
Focus Previous Search Result | ⇧F4 (Windows, Linux Shift+F4 ) | search.action.focusPreviousSearchResult |
Show Next Search Term | ↓ (Windows, Linux Down ) | history.showNext |
Show Previous Search Term | ↑ (Windows, Linux Up ) | history.showPrevious |
Search Editor
Command | Key | Command id |
---|---|---|
Open Results In Editor | ⌘Enter (Windows, Linux Alt+Enter ) | search.action.openInEditor |
Focus Search Editor Input | Escape | search.action.focusQueryEditorWidget |
Search Again | ⇧⌘R (Windows, Linux Ctrl+Shift+R ) | rerunSearchEditorSearch |
Delete File Results | ⇧⌘Backspace (Windows, Linux Ctrl+Shift+Backspace ) | search.searchEditor.action.deleteFileResults |
Preferences
Command | Key | Command id |
---|---|---|
Open Settings | ⌘, (Windows, Linux Ctrl+, ) | workbench.action.openSettings |
Open Workspace Settings | workbench.action.openWorkspaceSettings | |
Open Keyboard Shortcuts | ⌘K ⌘S (Windows, Linux Ctrl+K Ctrl+S ) | workbench.action.openGlobalKeybindings |
Open User Snippets | workbench.action.openSnippets | |
Select Color Theme | ⌘K ⌘T (Windows, Linux Ctrl+K Ctrl+T ) | workbench.action.selectTheme |
Configure Display Language | workbench.action.configureLocale |
Debug
Command | Key | Command id |
---|---|---|
Toggle Breakpoint | F9 | editor.debug.action.toggleBreakpoint |
Start | F5 | workbench.action.debug.start |
Continue | F5 | workbench.action.debug.continue |
Start (without debugging) | ⌃F5 (Windows, Linux Ctrl+F5 ) | workbench.action.debug.run |
Pause | F6 | workbench.action.debug.pause |
Step Into | F11 | workbench.action.debug.stepInto |
Tasks
Command | Key | Command id |
---|---|---|
Run Build Task | ⇧⌘B (Windows, Linux Ctrl+Shift+B ) | workbench.action.tasks.build |
Run Test Task | workbench.action.tasks.test |
Extensions
Command | Key | Command id |
---|---|---|
Install Extension | workbench.extensions.action.installExtension | |
Show Installed Extensions | workbench.extensions.action.showInstalledExtensions | |
Show Outdated Extensions | workbench.extensions.action.listOutdatedExtensions | |
Show Recommended Extensions | workbench.extensions.action.showRecommendedExtensions | |
Show Popular Extensions | workbench.extensions.action.showPopularExtensions | |
Update All Extensions | workbench.extensions.action.updateAllExtensions |
Next steps
Now that you know about our Key binding support, what’s next.
Common questions
How can I find out what command is bound to a specific key?
In the Keyboard Shortcut editor, you can filter on specific keystrokes to see which commands are bound to which keys. Below you can see that Ctrl+Shift+P is bound to Show All Commands to bring up the Command Palette.
How to add a key binding to an action, for example, add Ctrl+D to Delete Lines
Find a rule that triggers the action in the Default Keyboard Shortcuts and write a modified version of it in your keybindings.json file:
How can I add a key binding for only certain file types?
Use the editorLangId context key in your when clause:
I have modified my key bindings in keybindings.json ; why don’t they work?
Code Formatting in Visual Studio
Is there some combination of keys or a menu option that I can use to automatically format my code in Visual Studio?
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You could try the CodeMaid extension to Visual Studio.
This does code cleaning with the following steps:
Remove unused using statements
Sort using statements
Add unspecified access modifiers
Add blank line padding
Remove blank lines adjacent to braces
Run Visual Studio formatting
Remove consecutive blank lines
Remove end of line whitespace
Update endregion tags
So you get Visual Studio’s built-in reformatting plus lots of other tidying in one go. I expect there are other tools that do the same thing. I’ve been using CodeMaid for a while now and it’s both fast and reliable.
I guess you mean to format and indent the document nicely.
ctrl +E,D
If you really meant what JaredPar and Glenn are meaning you could also think about installing the PowerCommands for Visual Studio.
Also you should know that the keystroke of JaredPar and Glenn are not always working. Depending on what you selected at the first start of Visual Studio (are you a C#, VB, Web or Generic programmer) the keystrokes are slightly different.
If you selected C# developer the answer of Glenn and JaredPar works. If you selected generic or C++ developer only JaredPar answer works. If you took another role than maybe none of these keystrokes works and you have to check your keystroke through the menu at the position JaredPar mentioned.
Visual studio code format code
Key Bindings for Visual Studio Code
Visual Studio Code lets you perform most tasks directly from the keyboard. This page lists out the default bindings (keyboard shortcuts) and describes how you can update them.
Note: If you visit this page on a Mac, you will see the key bindings for the Mac. If you visit using Windows or Linux, you will see the keys for that platform. If you need the key bindings for another platform, hover your mouse over the key you are interested in.
Keyboard Shortcuts editor
Visual Studio Code provides a rich and easy keyboard shortcuts editing experience using Keyboard Shortcuts editor. It lists all available commands with and without keybindings and you can easily change / remove / reset their keybindings using the available actions. It also has a search box on the top that helps you in finding commands or keybindings. You can open this editor by going to the menu under File > Preferences > Keyboard Shortcuts. (Code > Preferences > Keyboard Shortcuts on macOS)
Most importantly, you can see keybindings according to your keyboard layout. For example, key binding kbstyle(Cmd+\) in US keyboard layout will be shown as kbstyle(Ctrl+Shift+Alt+Cmd+7) when layout is changed to German. The dialog to enter key binding will assign the correct and desired key binding as per your keyboard layout.
For doing more advanced keyboard shortcut customization, read Advanced Customization.
Keyboard shortcuts are vital to productivity and changing keyboarding habits can be tough. To help with this, File > Preferences > Migrate Keyboard Shortcuts from. shows you a list of popular keymap extensions. These extensions modify the VS Code shortcuts to match those of other editors so you don’t need to learn new keyboard shortcuts. There is also a Keymaps category of extensions in the Marketplace.
Tip: Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.
Keyboard Shortcuts Reference
We also have a printable version of these keyboard shortcuts. Help > Keyboard Shortcut Reference displays a condensed PDF version suitable for printing as an easy reference.
Below are links to the three platform-specific versions (US English keyboard):
Detecting keybinding conflicts
If you have many extensions installed or you have customized your keyboard shortcuts, you can sometimes have keybinding conflicts where the same keyboard shortcut is mapped to several commands. This can result in confusing behavior, especially if different keybindings are going in and out of scope as you move around the editor.
The Keyboard Shortcuts editor has a context menu command Show Same Keybindings, which will filter the keybindings based on a keyboard shortcut to display conflicts.
Pick a command with the keybinding you think is overloaded and you can see if multiple commands are defined, the source of the keybindings and when they are active.
To troubleshoot keybindings problems, you can execute the command Developer: Toggle Keyboard Shortcuts Troubleshooting. This will activate logging of dispatched keyboard shortcuts and will open an output panel with the corresponding log file.
You can then press your desired keybinding and check what keyboard shortcut VS Code detects and what command is invoked.
For example, when pressing cmd+/ in a code editor on macOS, the logging output would be:
Viewing modified keybindings
You can view any user modified keyboard shortcuts in VS Code in the Keyboard Shortcuts editor with the Show User Keybindings command in the More Actions (. ) menu. This applies the @source:user filter to the Keyboard Shortcuts editor (Source is ‘User’).
All keyboard shortcuts in VS Code can be customized via the keybindings.json file.
You can also open the keybindings.json file from the Command Palette ( kb(workbench.action.showCommands) ) with the Preferences: Open Keyboard Shortcuts (JSON) command.
Each rule consists of:
When a key is pressed:
The additional keybindings.json rules are appended at runtime to the bottom of the default rules, thus allowing them to overwrite the default rules. The keybindings.json file is watched by VS Code so editing it while VS Code is running will update the rules at runtime.
The keyboard shortcuts dispatching is done by analyzing a list of rules that are expressed in JSON. Here are some examples:
The key is made up of modifiers and the key itself.
The following modifiers are accepted:
The following keys are accepted:
You can invoke a command with arguments. This is useful if you often perform the same operation on a specific file or folder. You can add a custom keyboard shortcut to do exactly what you want.
The following is an example overriding the kbstyle(Enter) key to print some text:
The type command will receive <"text": "Hello World">as its first argument and add «Hello World» to the file instead of producing the default command.
For more information on commands that take arguments, refer to Built-in Commands.
Removing a specific key binding rule
Here is an example:
Note: This section relates only to key bindings, not to typing in the editor.
The keys above are string representations for virtual keys and do not necessarily relate to the produced character when they are pressed. More precisely:
Different keyboard layouts usually reposition the above virtual keys or change the characters produced when they are pressed. When using a different keyboard layout than the standard US, Visual Studio Code does the following:
All the key bindings are rendered in the UI using the current system’s keyboard layout. For example, Split Editor when using a French (France) keyboard layout is now rendered as kbstyle(Ctrl+*) :
Note: On Linux, Visual Studio Code detects your current keyboard layout on start-up and then caches this information. For a good experience, we recommend restarting VS Code if you change your keyboard layout.
Keyboard layout-independent bindings
Using scan codes, it is possible to define keybindings which do not change with the change of the keyboard layout. For example:
Accepted scan codes:
when clause contexts
VS Code gives you fine control over when your key bindings are enabled through the optional when clause. If your key binding doesn’t have a when clause, the key binding is globally available at all times. A when clause evaluates to either Boolean true or false for enabling key bindings.
You can also view a keybinding’s when clause directly in the Default Keybindings JSON (Preferences: Open Default Keyboard Shortcuts (JSON)):
For when clause conditional expressions, the following conditional operators are useful for keybindings:
You can find the full list of when clause conditional operators in the when clause contexts reference.
You can find some of the available when clause contexts in the when clause context reference.
The list there isn’t exhaustive and you can find other when clause contexts by searching and filtering in the Keyboard Shortcuts editor (Preferences: Open Keyboard Shortcuts ) or reviewing the Default Keybindings JSON file (Preferences: Open Default Keyboard Shortcuts (JSON)).
Custom keybindings for refactorings
The editor.action.codeAction command lets you configure keybindings for specific Refactorings (Code Actions). For example, the keybinding below triggers the Extract function refactoring Code Actions:
This is covered in depth in the Refactoring topic where you can learn about different kinds of Code Actions and how to prioritize them in the case of multiple possible refactorings.
Default Keyboard Shortcuts
You can view all default keyboard shortcuts in VS Code in the Keyboard Shortcuts editor with the Show Default Keybindings command in the More Actions (. ) menu. This applies the @source:default filter to the Keyboard Shortcuts editor (Source is ‘Default’).
You can view the default keyboard shortcuts as a JSON file using the command Preferences: Open Default Keyboard Shortcuts (JSON).
Some commands included below do not have default keyboard shortcuts and so are displayed as kbstyle(unassigned) but you can assign your own keybindings.
Command | Key | Command id |
---|---|---|
Cut line (empty selection) | kb(editor.action.clipboardCutAction) | editor.action.clipboardCutAction |
Copy line (empty selection) | kb(editor.action.clipboardCopyAction) | editor.action.clipboardCopyAction |
Paste | kb(editor.action.clipboardPasteAction) | editor.action.clipboardPasteAction |
Delete Line | kb(editor.action.deleteLines) | editor.action.deleteLines |
Insert Line Below | kb(editor.action.insertLineAfter) | editor.action.insertLineAfter |
Insert Line Above | kb(editor.action.insertLineBefore) | editor.action.insertLineBefore |
Move Line Down | kb(editor.action.moveLinesDownAction) | editor.action.moveLinesDownAction |
Move Line Up | kb(editor.action.moveLinesUpAction) | editor.action.moveLinesUpAction |
Copy Line Down | kb(editor.action.copyLinesDownAction) | editor.action.copyLinesDownAction |
Copy Line Up | kb(editor.action.copyLinesUpAction) | editor.action.copyLinesUpAction |
Undo | kb(undo) | undo |
Redo | kb(redo) | redo |
Add Selection To Next Find Match | kb(editor.action.addSelectionToNextFindMatch) | editor.action.addSelectionToNextFindMatch |
Move Last Selection To Next Find Match | kb(editor.action.moveSelectionToNextFindMatch) | editor.action.moveSelectionToNextFindMatch |
Undo last cursor operation | kb(cursorUndo) | cursorUndo |
Insert cursor at end of each line selected | kb(editor.action.insertCursorAtEndOfEachLineSelected) | editor.action.insertCursorAtEndOfEachLineSelected |
Select all occurrences of current selection | kb(editor.action.selectHighlights) | editor.action.selectHighlights |
Select all occurrences of current word | kb(editor.action.changeAll) | editor.action.changeAll |
Select current line | kb(expandLineSelection) | expandLineSelection |
Insert Cursor Below | kb(editor.action.insertCursorBelow) | editor.action.insertCursorBelow |
Insert Cursor Above | kb(editor.action.insertCursorAbove) | editor.action.insertCursorAbove |
Jump to matching bracket | kb(editor.action.jumpToBracket) | editor.action.jumpToBracket |
Indent Line | kb(editor.action.indentLines) | editor.action.indentLines |
Outdent Line | kb(editor.action.outdentLines) | editor.action.outdentLines |
Go to Beginning of Line | kb(cursorHome) | cursorHome |
Go to End of Line | kb(cursorEnd) | cursorEnd |
Go to End of File | kb(cursorBottom) | cursorBottom |
Go to Beginning of File | kb(cursorTop) | cursorTop |
Scroll Line Down | kb(scrollLineDown) | scrollLineDown |
Scroll Line Up | kb(scrollLineUp) | scrollLineUp |
Scroll Page Down | kb(scrollPageDown) | scrollPageDown |
Scroll Page Up | kb(scrollPageUp) | scrollPageUp |
Fold (collapse) region | kb(editor.fold) | editor.fold |
Unfold (uncollapse) region | kb(editor.unfold) | editor.unfold |
Fold (collapse) all subregions | kb(editor.foldRecursively) | editor.foldRecursively |
Unfold (uncollapse) all subregions | kb(editor.unfoldRecursively) | editor.unfoldRecursively |
Fold (collapse) all regions | kb(editor.foldAll) | editor.foldAll |
Unfold (uncollapse) all regions | kb(editor.unfoldAll) | editor.unfoldAll |
Add Line Comment | kb(editor.action.addCommentLine) | editor.action.addCommentLine |
Remove Line Comment | kb(editor.action.removeCommentLine) | editor.action.removeCommentLine |
Toggle Line Comment | kb(editor.action.commentLine) | editor.action.commentLine |
Toggle Block Comment | kb(editor.action.blockComment) | editor.action.blockComment |
Find | kb(actions.find) | actions.find |
Replace | kb(editor.action.startFindReplaceAction) | editor.action.startFindReplaceAction |
Find Next | kb(editor.action.nextMatchFindAction) | editor.action.nextMatchFindAction |
Find Previous | kb(editor.action.previousMatchFindAction) | editor.action.previousMatchFindAction |
Select All Occurrences of Find Match | kb(editor.action.selectAllMatches) | editor.action.selectAllMatches |
Toggle Find Case Sensitive | kb(toggleFindCaseSensitive) | toggleFindCaseSensitive |
Toggle Find Regex | kb(toggleFindRegex) | toggleFindRegex |
Toggle Find Whole Word | kb(toggleFindWholeWord) | toggleFindWholeWord |
Toggle Use of Tab Key for Setting Focus | kb(editor.action.toggleTabFocusMode) | editor.action.toggleTabFocusMode |
Toggle Render Whitespace | kb(toggleRenderWhitespace) | toggleRenderWhitespace |
Toggle Word Wrap | kb(editor.action.toggleWordWrap) | editor.action.toggleWordWrap |
Rich Languages Editing
Command | Key | Command id |
---|---|---|
Trigger Suggest | kb(editor.action.triggerSuggest) | editor.action.triggerSuggest |
Trigger Parameter Hints | kb(editor.action.triggerParameterHints) | editor.action.triggerParameterHints |
Format Document | kb(editor.action.formatDocument) | editor.action.formatDocument |
Format Selection | kb(editor.action.formatSelection) | editor.action.formatSelection |
Go to Definition | kb(editor.action.revealDefinition) | editor.action.revealDefinition |
Show Hover | kb(editor.action.showHover) | editor.action.showHover |
Peek Definition | kb(editor.action.peekDefinition) | editor.action.peekDefinition |
Open Definition to the Side | kb(editor.action.revealDefinitionAside) | editor.action.revealDefinitionAside |
Quick Fix | kb(editor.action.quickFix) | editor.action.quickFix |
Go to References | kb(editor.action.goToReferences) | editor.action.goToReferences |
Rename Symbol | kb(editor.action.rename) | editor.action.rename |
Replace with Next Value | kb(editor.action.inPlaceReplace.down) | editor.action.inPlaceReplace.down |
Replace with Previous Value | kb(editor.action.inPlaceReplace.up) | editor.action.inPlaceReplace.up |
Expand AST Selection | kb(editor.action.smartSelect.expand) | editor.action.smartSelect.expand |
Shrink AST Selection | kb(editor.action.smartSelect.shrink) | editor.action.smartSelect.shrink |
Trim Trailing Whitespace | kb(editor.action.trimTrailingWhitespace) | editor.action.trimTrailingWhitespace |
Change Language Mode | kb(workbench.action.editor.changeLanguageMode) | workbench.action.editor.changeLanguageMode |
Command | Key | Command id |
---|---|---|
Show All Symbols | kb(workbench.action.showAllSymbols) | workbench.action.showAllSymbols |
Go to Line. | kb(workbench.action.gotoLine) | workbench.action.gotoLine |
Go to File. Quick Open | kb(workbench.action.quickOpen) | workbench.action.quickOpen |
Go to Symbol. | kb(workbench.action.gotoSymbol) | workbench.action.gotoSymbol |
Show Problems | kb(workbench.actions.view.problems) | workbench.actions.view.problems |
Go to Next Error or Warning | kb(editor.action.marker.nextInFiles) | editor.action.marker.nextInFiles |
Go to Previous Error or Warning | kb(editor.action.marker.prevInFiles) | editor.action.marker.prevInFiles |
Show All Commands | kb(workbench.action.showCommands) or kbstyle(F1) | workbench.action.showCommands |
Navigate Editor Group History | kb(workbench.action.quickOpenPreviousRecentlyUsedEditorInGroup) | workbench.action.quickOpenPreviousRecentlyUsedEditorInGroup |
Go Back | kb(workbench.action.navigateBack) | workbench.action.navigateBack |
Go back in Quick Input | kb(workbench.action.quickInputBack) | workbench.action.quickInputBack |
Go Forward | kb(workbench.action.navigateForward) | workbench.action.navigateForward |
Command | Key | Command id |
---|---|---|
New Window | kb(workbench.action.newWindow) | workbench.action.newWindow |
Close Window | kb(workbench.action.closeWindow) | workbench.action.closeWindow |
Close Editor | kb(workbench.action.closeActiveEditor) | workbench.action.closeActiveEditor |
Close Folder | kb(workbench.action.closeFolder) | workbench.action.closeFolder |
Cycle Between Editor Groups | kb(workbench.action.navigateEditorGroups) | workbench.action.navigateEditorGroups |
Split Editor | kb(workbench.action.splitEditor) | workbench.action.splitEditor |
Focus into First Editor Group | kb(workbench.action.focusFirstEditorGroup) | workbench.action.focusFirstEditorGroup |
Focus into Second Editor Group | kb(workbench.action.focusSecondEditorGroup) | workbench.action.focusSecondEditorGroup |
Focus into Third Editor Group | kb(workbench.action.focusThirdEditorGroup) | workbench.action.focusThirdEditorGroup |
Focus into Editor Group on the Left | kb(workbench.action.focusPreviousGroup) | workbench.action.focusPreviousGroup |
Focus into Editor Group on the Right | kb(workbench.action.focusNextGroup) | workbench.action.focusNextGroup |
Move Editor Left | kb(workbench.action.moveEditorLeftInGroup) | workbench.action.moveEditorLeftInGroup |
Move Editor Right | kb(workbench.action.moveEditorRightInGroup) | workbench.action.moveEditorRightInGroup |
Move Active Editor Group Left | kb(workbench.action.moveActiveEditorGroupLeft) | workbench.action.moveActiveEditorGroupLeft |
Move Active Editor Group Right | kb(workbench.action.moveActiveEditorGroupRight) | workbench.action.moveActiveEditorGroupRight |
Move Editor into Next Group | kb(workbench.action.moveEditorToNextGroup) | workbench.action.moveEditorToNextGroup |
Move Editor into Previous Group | kb(workbench.action.moveEditorToPreviousGroup) | workbench.action.moveEditorToPreviousGroup |
Command | Key | Command id |
---|---|---|
New File | kb(workbench.action.files.newUntitledFile) | workbench.action.files.newUntitledFile |
Open File. | kb(workbench.action.files.openFile) | workbench.action.files.openFile |
Save | kb(workbench.action.files.save) | workbench.action.files.save |
Save All | kb(saveAll) | saveAll |
Save As. | kb(workbench.action.files.saveAs) | workbench.action.files.saveAs |
Close | kb(workbench.action.closeActiveEditor) | workbench.action.closeActiveEditor |
Close Others | kb(workbench.action.closeOtherEditors) | workbench.action.closeOtherEditors |
Close Group | kb(workbench.action.closeEditorsInGroup) | workbench.action.closeEditorsInGroup |
Close Other Groups | kb(workbench.action.closeEditorsInOtherGroups) | workbench.action.closeEditorsInOtherGroups |
Close Group to Left | kb(workbench.action.closeEditorsToTheLeft) | workbench.action.closeEditorsToTheLeft |
Close Group to Right | kb(workbench.action.closeEditorsToTheRight) | workbench.action.closeEditorsToTheRight |
Close All | kb(workbench.action.closeAllEditors) | workbench.action.closeAllEditors |
Reopen Closed Editor | kb(workbench.action.reopenClosedEditor) | workbench.action.reopenClosedEditor |
Keep Open | kb(workbench.action.keepEditor) | workbench.action.keepEditor |
Copy Path of Active File | kb(workbench.action.files.copyPathOfActiveFile) | workbench.action.files.copyPathOfActiveFile |
Reveal Active File in Windows | kb(workbench.action.files.revealActiveFileInWindows) | workbench.action.files.revealActiveFileInWindows |
Show Opened File in New Window | kb(workbench.action.files.showOpenedFileInNewWindow) | workbench.action.files.showOpenedFileInNewWindow |
Compare Opened File With | kb(workbench.files.action.compareFileWith) | workbench.files.action.compareFileWith |
Command | Key | Command id |
---|---|---|
Toggle Full Screen | kb(workbench.action.toggleFullScreen) | workbench.action.toggleFullScreen |
Toggle Zen Mode | kb(workbench.action.toggleZenMode) | workbench.action.toggleZenMode |
Leave Zen Mode | kb(workbench.action.exitZenMode) | workbench.action.exitZenMode |
Zoom in | kb(workbench.action.zoomIn) | workbench.action.zoomIn |
Zoom out | kb(workbench.action.zoomOut) | workbench.action.zoomOut |
Reset Zoom | kb(workbench.action.zoomReset) | workbench.action.zoomReset |
Toggle Sidebar Visibility | kb(workbench.action.toggleSidebarVisibility) | workbench.action.toggleSidebarVisibility |
Show Explorer / Toggle Focus | kb(workbench.view.explorer) | workbench.view.explorer |
Show Search | kb(workbench.view.search) | workbench.view.search |
Show Source Control | kb(workbench.view.scm) | workbench.view.scm |
Show Run | kb(workbench.view.debug) | workbench.view.debug |
Show Extensions | kb(workbench.view.extensions) | workbench.view.extensions |
Show Output | kb(workbench.action.output.toggleOutput) | workbench.action.output.toggleOutput |
Quick Open View | kb(workbench.action.quickOpenView) | workbench.action.quickOpenView |
Open New Command Prompt | kb(workbench.action.terminal.openNativeConsole) | workbench.action.terminal.openNativeConsole |
Toggle Markdown Preview | kb(markdown.showPreview) | markdown.showPreview |
Open Preview to the Side | kb(markdown.showPreviewToSide) | markdown.showPreviewToSide |
Toggle Integrated Terminal | kb(workbench.action.terminal.toggleTerminal) | workbench.action.terminal.toggleTerminal |
Command | Key | Command id |
---|---|---|
Show Search | kb(workbench.view.search) | workbench.view.search |
Replace in Files | kb(workbench.action.replaceInFiles) | workbench.action.replaceInFiles |
Toggle Match Case | kb(toggleSearchCaseSensitive) | toggleSearchCaseSensitive |
Toggle Match Whole Word | kb(toggleSearchWholeWord) | toggleSearchWholeWord |
Toggle Use Regular Expression | kb(toggleSearchRegex) | toggleSearchRegex |
Toggle Search Details | kb(workbench.action.search.toggleQueryDetails) | workbench.action.search.toggleQueryDetails |
Focus Next Search Result | kb(search.action.focusNextSearchResult) | search.action.focusNextSearchResult |
Focus Previous Search Result | kb(search.action.focusPreviousSearchResult) | search.action.focusPreviousSearchResult |
Show Next Search Term | kb(history.showNext) | history.showNext |
Show Previous Search Term | kb(history.showPrevious) | history.showPrevious |
Command | Key | Command id |
---|---|---|
Open Results In Editor | kb(search.action.openInEditor) | search.action.openInEditor |
Focus Search Editor Input | kb(search.action.focusQueryEditorWidget) | search.action.focusQueryEditorWidget |
Search Again | kb(rerunSearchEditorSearch) | rerunSearchEditorSearch |
Delete File Results | kb(search.searchEditor.action.deleteFileResults) | search.searchEditor.action.deleteFileResults |
Command | Key | Command id |
---|---|---|
Open Settings | kb(workbench.action.openSettings) | workbench.action.openSettings |
Open Workspace Settings | kb(workbench.action.openWorkspaceSettings) | workbench.action.openWorkspaceSettings |
Open Keyboard Shortcuts | kb(workbench.action.openGlobalKeybindings) | workbench.action.openGlobalKeybindings |
Open User Snippets | kb(workbench.action.openSnippets) | workbench.action.openSnippets |
Select Color Theme | kb(workbench.action.selectTheme) | workbench.action.selectTheme |
Configure Display Language | kb(workbench.action.configureLocale) | workbench.action.configureLocale |
Command | Key | Command id |
---|---|---|
Toggle Breakpoint | kb(editor.debug.action.toggleBreakpoint) | editor.debug.action.toggleBreakpoint |
Start | kb(workbench.action.debug.start) | workbench.action.debug.start |
Continue | kb(workbench.action.debug.continue) | workbench.action.debug.continue |
Start (without debugging) | kb(workbench.action.debug.run) | workbench.action.debug.run |
Pause | kb(workbench.action.debug.pause) | workbench.action.debug.pause |
Step Into | kb(workbench.action.debug.stepInto) | workbench.action.debug.stepInto |
Command | Key | Command id |
---|---|---|
Run Build Task | kb(workbench.action.tasks.build) | workbench.action.tasks.build |
Run Test Task | kb(workbench.action.tasks.test) | workbench.action.tasks.test |
Command | Key | Command id |
---|---|---|
Install Extension | kb(workbench.extensions.action.installExtension) | workbench.extensions.action.installExtension |
Show Installed Extensions | kb(workbench.extensions.action.showInstalledExtensions) | workbench.extensions.action.showInstalledExtensions |
Show Outdated Extensions | kb(workbench.extensions.action.listOutdatedExtensions) | workbench.extensions.action.listOutdatedExtensions |
Show Recommended Extensions | kb(workbench.extensions.action.showRecommendedExtensions) | workbench.extensions.action.showRecommendedExtensions |
Show Popular Extensions | kb(workbench.extensions.action.showPopularExtensions) | workbench.extensions.action.showPopularExtensions |
Update All Extensions | kb(workbench.extensions.action.updateAllExtensions) | workbench.extensions.action.updateAllExtensions |
Now that you know about our Key binding support, what’s next.
How can I find out what command is bound to a specific key?
In the Keyboard Shortcut editor, you can filter on specific keystrokes to see which commands are bound to which keys. Below you can see that kbstyle(Ctrl+Shift+P) is bound to Show All Commands to bring up the Command Palette.
How to add a key binding to an action, for example, add Ctrl+D to Delete Lines
Find a rule that triggers the action in the Default Keyboard Shortcuts and write a modified version of it in your keybindings.json file:
How can I add a key binding for only certain file types?
Use the editorLangId context key in your when clause:
I have modified my key bindings in keybindings.json ; why don’t they work?
Visual Studio Code doesn’t format C# code
I created a new file, set the C# language, and wrote some code. Then I pressed Ctrl + Shift + F (or F1 → Format Document). And got I the error
Sorry, but there is no formatter for ‘csharp’-files installed.
Also, I installed C# Extension, but it didn’t help. The Visual Studio Code version is 1.18.0.
18 Answers 18
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you have prettier as the default formatter as I do, you should do this:
Then click to «open settings (JSON)»:
This is where you should paste the below snippet.
This is my config:
For you to apply this configuration you need c# extension.
This works for me.
Note: If it is true then clear the checkbox and set it to true again. After that, you must restart Visual Studio Code.
Menu File → Preferences → Settings →
3/4/5 unity engine projects on mac
Browse the Visual Studio Code extension library, and make sure you’ve got the C# extension installed ms-dotnettools.csharp
Restart Visual Studio Code. It should now make code auto-format when you complete the line with a semicolon, or when you close the outer brace of a scope.
Note: this is a global setting for the editor, so it may enable auto-formatting for other languages and not just C#.
This was tested on Visual Studio Code version 1.43.1.
Format html code in Visual Studio Code such that attributes are on separate lines?
There seems to be a lack of formatting settings for vscode. I want to be able to format html such that my html shows up as:
This is one functionality that I’d really love to have!
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
VSCode added a way to do this now. You can edit your settings.json (ctrl+shift+p) and then add the following for the desired effect:
force-aligned will also add indents to align it with the attribute on the line where tag was opened.
Visit this link for more details or updates.
My extended html was being limited by the «Prettier: Print width» setting, I thought I’d put a random value as 0, but then all the tags start breaking the attributes. So he put 10,000. This solved my problem.
There are differnt «formatter» extensions, but one I found does a decent job of this exact formatting that you are looking for. It’s called «vscode-tidyhtml«.
It should format HTML so that attributes are on different lines. I am not sure if it works well for other file types.
Параметры стиля кода
Код стиля параметров каждого проекта можно определить с помощью EDITORCONFIG-файла; для всего кода в Visual Studio можно задать настройки на странице Параметры в текстовом редакторе. Для кода на C# можно также настроить Visual Studio, чтобы применять эти параметры стиля кода с помощью команд Очистка кода (Visual Studio 2019, Visual Studio 2022) и Форматировать документ (Visual Studio 2017).
Этот раздел относится к Visual Studio в Windows. Информацию о Visual Studio для Mac см. в статье Поведение редактора в Visual Studio для Mac.
Стили кода в EDITORCONFIG-файлах
Вы можете вручную отредактировать файл EditorConfig или автоматически создать его в зависимости от установленных в Visual Studio параметров стиля кода в диалоговом окне Параметры. Эта страница параметров доступна втекстовом редакторе> параметров инструментов> > [C# или Basic] >Code Style>General. Нажмите кнопку Создать EDITORCONFIG-файл из параметров, чтобы автоматически создать EDITORCONFIG-файл стиля кода на основе параметров, которые вы задали на этой странице Параметры.
Вы можете вручную отредактировать файл EditorConfig или автоматически создать его в зависимости от установленных в Visual Studio параметров стиля кода в диалоговом окне Параметры. Эта страница параметров доступна втекстовом редакторе> параметров инструментов> > [C# или Visual Basic] >Code Style>General. Нажмите кнопку Создать EDITORCONFIG-файл из параметров, чтобы автоматически создать EDITORCONFIG-файл стиля кода на основе параметров, которые вы задали на этой странице Параметры.
Стили кода в диалоговом окне «Параметры»
Параметры стиля кода для проектов C# и Visual Basic можно задать, открыв диалоговое окно Параметры из меню Сервис. В диалоговом окне «Параметры» выберите текстовый редактор> [C# или Visual Basic] >«Общий стиль> кода».
Параметры стиля кода для проектов C# и Visual Basic можно задать, открыв диалоговое окно Параметры из меню Сервис. В диалоговом окне «Параметры» выберите текстовый редактор> [C# или Basic] > Code StyleGeneral(Общие) стиль> кода.
При выборе для каждого из элементов в списке выводится окно предварительного просмотра:
Параметры, заданные в этом окне, применяются к вашей учетной записи персонализации Visual Studio и не связаны с конкретным проектом или базой кода. Кроме того, они не применяются во время сборки, в том числе в сборках с непрерывной интеграцией (CI). Если вы хотите связать предпочтения к стилю кода со своим проектом и применяете стили во время сборки, укажите такие предпочтения в EDITORCONFIG-файле, связанном с проектом.
Предпочтения и степень серьезности
Для каждого параметра стиля кода на этой странице с помощью раскрывающихся списков в каждой строке можно задать значения для параметров Предпочтение и Серьезность. Для серьезности можно задать значения Только рефакторинг, Предложение, Предупреждение или Ошибка. Если вы хотите включить быстрые действия для стиля кода, убедитесь, что для параметра Серьезность задано значение, отличное от Только рефакторинг. Лампочка быстрых действий, лампочка
ошибки или значок отвертки
появляется, когда используется не предпочтительный стиль, и вы можете выбрать параметр в списке быстрых действий, чтобы автоматически переписать код в предпочитаемый стиль.
Принудительное применение стиля кода в сборке
Применение стилей кода
Для файлов кода на C# в Visual Studio есть кнопка Очистка кода в нижней части редактора (сочетание клавиш: CTRL+K, CTRL+E) для применения стилей кода из EDITORCONFIG-файла или со страницы параметров стиля кода. Если EDITORCONFIG-файл существует в проекте, его параметры имеют приоритет.
Правила, настроенные с серьезностью Нет, не используются в ходе очистки кода, но могут применяться по отдельности через меню Быстрые действия и рефакторинг.
Во-первых, настройте стили кода, которые необходимо применять (в одном из двух профилей), используя диалоговое окно Настройка очистки кода. Чтобы открыть это диалоговое окно, щелкните стрелку рядом со значком метлы (очистка кода) и выберите команду Настроить очистку кода.
После настройки очистки кода вы можете щелкнуть значок метлы или нажать клавиши Ctrl+K, Ctrl+E, чтобы запустить очистку кода. Вы также можете выполнить очистку кода для всего проекта или решения сразу. Щелкните правой кнопкой мыши имя проекта или решения в обозревателе решений, выберите команду Анализ и очистка кода, а затем — Запустить очистку кода.
Для файлов кода на C# в Visual Studio есть кнопка Очистка кода в нижней части редактора (сочетание клавиш: CTRL+K, CTRL+E) для применения стилей кода из EDITORCONFIG-файла или со страницы параметров стиля кода. Если EDITORCONFIG-файл существует в проекте, его параметры имеют приоритет.
Правила, настроенные с серьезностью Нет, не используются в ходе очистки кода, но могут применяться по отдельности через меню Быстрые действия и рефакторинг.
Во-первых, настройте стили кода, которые необходимо применять (в одном из двух профилей), используя диалоговое окно Настройка очистки кода. Чтобы открыть это диалоговое окно, щелкните стрелку рядом со значком метлы (очистка кода) и выберите команду Настроить очистку кода.
После настройки очистки кода вы можете щелкнуть значок метлы или нажать клавиши Ctrl+K, Ctrl+E, чтобы запустить очистку кода. Вы также можете выполнить очистку кода для всего проекта или решения сразу. Щелкните правой кнопкой мыши имя проекта или решения в обозревателе решений, выберите команду Анализ и очистка кода, а затем — Запустить очистку кода.
Параметры очистки кода
Параметр | Параметр «Идентификатор правила» или «Стиль» |
---|---|
Удаление ненужных операций импорта или использования | IDE0005 |
Применение параметров заголовка файла | file_header_template |
Удаление неиспользуемых переменных | IDE0051 |
Применение параметров создания объектов | visual_basic_style_prefer_simplified_object_creation |
Применение параметров IsNot | visual_basic_style_prefer_isnot_expression |
Добавление квалификации «this» или «Me» | IDE0003-IDE0009 |
Добавить модификаторы доступа | dotnet_style_require_accessibility_modifiers |
Модификаторы Order | IDE0036 |
Создание поля только для чтения | dotnet_style_readonly_field |
Удалить лишние операции приведения | IDE0004 |
Применение параметров инициализации объекта или коллекции) | dotnet_style_object_initializer |
Применение параметров размещения директив using | csharp_using_directive_placement |
Применение настроек круглых скобок | IDE0047-IDE0048 |
Применение параметров неиспользуемых значений | IDE0058 |
Применить настройки типа языка или платформы | IDE0049 |
Удаление неиспользуемых подавлений | dotnet_remove_unnecessary_suppression_exclusions |
Применение логического выражения | dotnet_style_prefer_simplified_boolean_expressions |
Применение параметров интерполяции строк | dotnet_style_prefer_simplified_interpolation |
Удаление неиспользуемых параметров | dotnet_code_quality_unused_parameters |
Применение параметров автоматического свойства | dotnet_style_prefer_auto_properties |
Применение параметров составного назначения | dotnet_style_prefer_compound_assignment |
Применение параметров выражения объединения | dotnet_style_coalesce_expression |
Применение параметров условного выражения | dotnet_style_prefer_conditional_expression_over_assignment dotnet_style_prefer_conditional_expression_over_return |
Применение параметров имени кортежа | dotnet_style_explicit_tuple_names dotnet_style_prefer_inferred_tuple_names |
Применение параметров имен членов анонимного типа | dotnet_style_prefer_inferred_anonymous_type_member_names |
Применение параметров проверки null | dotnet_style_prefer_is_null_check_over_reference_equality_method |
Применение параметров распространения NULL | dotnet_style_null_propagation |
Применение параметров var | IDE0007-IDE0008 |
Добавление обязательных фигурных скобок для операторов однострочного элемента управления | csharp_prefer_braces |
Применить настройки тела выражения или блока | Элементы, воплощающие выражение |
Применить настройки встроенных выходных переменных | csharp_style_inlined_variable_declaration |
Применение параметров сопоставления шаблонов | Параметры сопоставления шаблонов |
Применение параметров вызова условного делегата | csharp_style_conditional_delegate_call |
Применение параметров статической локальной функции | csharp_prefer_static_local_function |
Применение параметров деконструккции | csharp_style_deconstructed_variable_declaration |
Применение параметров по умолчанию (T) | csharp_prefer_simple_default_expression |
Применение параметров new() | csharp_style_implicit_object_creation_when_type_is_apparent |
Применение параметров диапазона | csharp_style_prefer_range_operator |
Применение локальных параметров анонимной функции | csharp_style_pattern_local_over_anonymous_function |
Применение параметров NULL | Параметры проверки NULL |
Применение параметров инструкции using | csharp_prefer_simple_using_statement |
Применение параметров выражения throw | csharp_style_throw_expression |
Если вы хотите, чтобы параметры стиля кода применялись при каждом сохранении файла, перейдите в> раздел«Параметры очистки кода«> и выберите «Выполнить профиль очистки кода» при сохранении.
Если вы хотите применять параметры стиля кода при каждом сохранении файла, вам может подойти расширение для очистки кода при сохранении.
Format code command for PHP/HTML in Visual Studio Code
Is it possible to get Visual Studio Code to format mixed HTML and PHP code on Windows Visual Studio Code version 0.7.1?
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Update 2021-07-21
The free version of Intelephense supports code formatting with the usual shortcuts ( Alt + Shift + F on Windows and Linux, ⌥⇧F on macOS). Visual Studio Code continues to lack built-in support for PHP code formatting and will direct you to the extension marketplace if you attempt to format PHP without an appropriate extension installed.
Original answer
Visual Studio Code has pretty awesome PHP support. What it lacks is covered by extensions. A quick search reveals at least three (1, 2, and 3) that claim to support PHP formatting.
They mostly seem to use the standard shortcut of Alt + Shift + F on Windows/Linux, with varying shortcuts on Mac. If you’re on Mac, give ⌥⇧F a try.
Auto format C# code In Visual Studio Code
This is the sample code output I need to achieve:
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I have found an option which makes it easier to format code while typing.
I applied the below settings in workspace settings:
This works fine for me.
Go to menu File → Preference → Settings.
Search for format
Select the options you would like:
Format on Paste
Close the Settings window.
You can also see it in your settings.json file:
Click on the keybindings.json link:
Enter the below binding for the Enter key. This binding will overwrite the defaults for current user.
Add macros to User Settings :
And the below key binding to keybindings.json :
Code formatters available on Visual Studio default as
If you again wish to do it when pressing Enter you need to set up your workspace preferences and then configure the key bindings:
It now formats the whole document if nothing is selected, and else it formats the selection.
Also there is the beautify.onSave, editor.formatOnSave option. Please try that too to make the code pretty.
Edit: This doesn’t actually work because this will suppress the regular Enter key behavior
To get this to work for me I had to install two extensions
Without the second extension I was getting the error visual studio code there is no formatter for ‘csharp’-files installed
I also made sure my Visual Studio Code was up to date (menu* → Help → Restart and Update or Check for Updates)
Then I added a custom key binding. menu File → Preferences → Keyboard Shortcuts → «For advanced customizations open and edit keybindings.json»:
I had to type in the word enter because the dialog to capture keys doesn’t acknowledge it.
Как форматировать код в Visual Studio Code (VSCode)
что эквивалентно Ctrl + K + F и Ctrl + K + D в Windows в Visual Studio для форматирования или» украшения » кода в редакторе кода Visual Studio?
30 ответов
форматирование кода доступно в VS Code через следующие ярлыки:
кроме того, вы можете найти ярлык, а также другие ярлыки, через поиск функциональность, предоставляемая в редакторе с Ctrl + Shift + P (или команда + Shift + P на Mac), а затем поиск документ в формате.
Ярлык Форматирования Кода:
вы также можете настроить этот ярлык через настройки, если это необходимо.
Форматирование Кода Сохранение файла:
Visual Studio code позволяет пользователю настраивать параметры по умолчанию.
Если вы хотите автоматически форматировать содержимое при сохранении, добавьте этот фрагмент кода ниже в параметры рабочего пространства кода visual studio.
Примечание: теперь вы можете автоматически форматировать файлы typescript проверить мое обновление
Format code command for PHP/HTML in Visual Studio Code
Is it possible to get Visual Studio Code to format mixed HTML and PHP code on Windows Visual Studio Code version 0.7.1?
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Update 2021-07-21
The free version of Intelephense supports code formatting with the usual shortcuts ( Alt + Shift + F on Windows and Linux, ⌥⇧F on macOS). Visual Studio Code continues to lack built-in support for PHP code formatting and will direct you to the extension marketplace if you attempt to format PHP without an appropriate extension installed.
Original answer
Visual Studio Code has pretty awesome PHP support. What it lacks is covered by extensions. A quick search reveals at least three (1, 2, and 3) that claim to support PHP formatting.
They mostly seem to use the standard shortcut of Alt + Shift + F on Windows/Linux, with varying shortcuts on Mac. If you’re on Mac, give ⌥⇧F a try.
Creating a Formatter Extension
November 21, 2016 by Johannes Rieken, @johannesrieken
Since its introduction, the Visual Studio Code extension API has provided support for source code formatters. The first language extensions we built, for example TypeScript, C# and Go, used the formatting API. We wrote this blog to explain the best practices for implementing formatters.
VS Code’s extension API follows a set of guiding principles. The essence of these principles is that VS Code provides the skeleton and extensions provide the «smarts». The common pattern is for VS Code to provide the UI around a feature and the extensions provide the necessary data to make it shine.
The core benefit of using the extension API for implementing a formatter comes from the exposure of the Format Document and Format Selection actions. These actions are available in the editor context menu, bound to keyboard shortcuts, and visible in the Command Palette. Using the API leads to a consistent user experience across all formatter extensions.
The Formatting API
The code snippets below show what to do and what not to do when implementing a formatter. The best practice is to use the formatting API and not create a new action, such as «Format Foo File.» The full extension example can be found on GitHub.
Recently, we added the «Format on Save» feature. An extension properly implementing the formatting API supports this feature without any new code.
Tip: To take advantage of this, a formatting extension needs to be registered using the registerDocumentFormattingEditProvider API call.
Multiple Formatters
A common misunderstanding is that when contributing a formatter, you must support all programming languages. When an extension registers as a formatter with registerDocumentFormattingEditProvider, it indicates with a DocumentSelector which programming languages it supports. With that information, the editor can enable the formatting actions when for example, an HTML document is open. Likewise, the editor will disable the formatting actions when displaying documents for which no formatter is registered.
What happens when there are multiple formatters for one language? This can be a problem when different formatters’ actions contradict. In the October release, we added settings to enable or disable the default formatters that ship with VS Code. The best practice is for extension authors to add a similar setting as what we did in VS Code as shown below.
An extension adds settings through the contributes.configuration extension point.
Formatters in the Marketplace
Last, we want to bring more awareness to formatters and have added a new «Formatters» category to the Marketplace. We have seeded it with popular formatting extensions and invite formatter authors to add theirs as well. You can also use extension packs to bundle a formatter extension with other extensions for your favorite language.
Summary
To summarize, an extension that implements the formatting extension API properly will do the following :
We are not done with the feature work for formatters. «Format on Paste», «Format Files in Folder» and more are on our roadmap and we are happily awaiting more of your feedback and ideas.
Johannes Rieken, VS Code Team Member
@johannesrieken
Automatically reformat Python code in Visual Studio
Visual Studio lets you quickly reformat code to match pre-configured formatting options.
Define formatting rules
You can set your formatting options through the menus Tools > Options > Text Editor > Python > Formatting and its nested tabs. Formatting options by default are set to match a superset of the PEP 8 style guide. The General tab determines when formatting is applied; settings for the other three tabs are described in this article.
You need to select Show all settings for these options to appear:
Python support in Visual Studio also adds the useful Fill Comment Paragraph command to the Edit > Advanced menu as described in a later section.
Apply format to selection or file
To format a selection:
To format the whole file:
Spacing examples
Spacing controls where spaces are inserted or removed around various language constructs. Each option has three possible values:
Examples for the various options are provided in the following tables:
Statement options
The Statements options control automatic rewriting of various statements into more Pythonic forms.
Option | Before formatting | After formatting |
---|---|---|
Place imported modules on new line | import sys, pickle | import sys import pickle |
Remove unnecessary semicolons | x = 42; | x = 42 |
Place multiple statements on new lines | x = 42; y = 100 | x = 42 y = 100 |
Wrapping options
Wrapping lets you set the Maximum comment width (default is 80). If the Wrap comments that are too wide option is set, Visual Studio reformats comments to not exceed that maximum width.
Format comment text
Edit > Advanced > Fill Comment Paragraph (Ctrl+E > P) reflows and formats comment text, combining short lines together and breaking up long ones.
Visual studio Reformat Code/Document
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You can use Edit > Advanced > Format Document and you can also move this as a button to any toolbar. Go to Tools > Customize > Commands, select Toolbar and push Add Command button. Then select Edit category and find Document Format.
Apparently VS2010 (maybe others) hide certain commands depending on the style you choose. I chose Web Dev (code) as my choice and the Document Format is not present to be added to a toolbar. But, if I change to C# Code (tools>Import/Export) then the Document Format command is right there in the Edit menu where others here have said it is.
I had to import the C# Dev layout, but unchecked colors and code formatting options (so it won’t overwrite those). What section you must import to get the format document button, I don’t know, I didn’t experiment that deep.
Seems stupid MS chose to force us down specific paths for layout with no convenient way to get out of it.
How do you auto format code in Visual Studio?
I know Visual Studio can auto format to make my methods and loops indented properly, but I cannot find the setting.
38 Answers 38
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you can afford it (or if you’re eligible for the 30-day free trial) JetBrains’ ReSharper can reformat a whole project directory.
Just install → right-click a directory → select Cleanup Code from the context menu.
You can also try the right click menu (context menu) option to format the selection of the coding document. Take a look at the below screenshot:
In Windows, use the following:
Menu Edit → Advanced → Format Document
If you are using JetBrains ReSharper, the easiest way to format your code is to use the CTRL + ALT + ENTER shortcut (Reformat code).
Using VS 2017 I wanted to format web page HTML which somehow had become entirely left aligned. Even after installing Productivity Power Tools this wouldn’t work.
Cut/Paste of a section is another quick way (and easy to remember).
Simply hitting Ctrl + Shift + I will do the job.
Visual Studio Code Tips and Tricks
«Tips and Tricks» lets you jump right in and learn how to be productive with Visual Studio Code. You’ll become familiar with its powerful editing, code intelligence, and source code control features and learn useful keyboard shortcuts. This topic goes pretty fast and provides a broad overview, so be sure to look at the other in-depth topics in Getting Started and the User Guide to learn more.
If you don’t have Visual Studio Code installed, go to the Download page. You can find platform specific setup instructions at Running VS Code on Linux, macOS, and Windows.
Prefer a video? You can watch a recent Microsoft Build talk Visual Studio Code tips and tricks, which describes 20 tips and tricks for working productively with VS Code.
Basics
Getting started
The best way of exploring VS Code hands-on is to open the Get Started page. You will get an overview of VS Code’s customizations and features. Help > Get Started.
Pick a Walkthrough for a self-guided tour through the setup steps, features, and deeper customizations that VS Code offers. As you discover and learn, the walkthroughs track your progress.
If you are looking to improve your code editing skills open the Interactive Editor Playground. Try out VS Code’s code editing features, like multi-cursor editing, IntelliSense, Snippets, Emmet, and many more. Help > Editor Playground.
Command Palette
Access all available commands based on your current context.
Keyboard Shortcut: ⇧⌘P (Windows, Linux Ctrl+Shift+P )
Default keyboard shortcuts
All of the commands are in the Command Palette with the associated key binding (if it exists). If you forget a keyboard shortcut, use the Command Palette to help you out.
Keyboard reference sheets
Download the keyboard shortcut reference sheet for your platform (macOS, Windows, Linux).
Quick Open
Quickly open files.
Keyboard Shortcut: ⌘P (Windows, Linux Ctrl+P )
Typing commands such as edt and term followed by a space will bring up dropdown lists.
Navigate between recently opened files
Repeat the Quick Open keyboard shortcut to cycle quickly between recently opened files.
Open multiple files from Quick Open
You can open multiple files from Quick Open by pressing the Right arrow key. This will open the currently selected file in the background and you can continue selecting files from Quick Open.
Navigate between recently opened folders and workspaces
Keyboard Shortcut: ⌃R (Windows, Linux Ctrl+R )
Displays a Quick Pick dropdown with the list from File > Open Recent with recently opened folders and workspaces followed by files.
Command line
VS Code has a powerful command line interface (CLI) which allows you to customize how the editor is launched to support various scenarios.
Make sure the VS Code binary is on your path so you can simply type ‘code’ to launch VS Code. See the platform specific setup topics if VS Code is added to your environment path during installation (Running VS Code on Linux, macOS, Windows).
.vscode folder
Status Bar
Errors and warnings
Keyboard Shortcut: ⇧⌘M (Windows, Linux Ctrl+Shift+M )
Quickly jump to errors and warnings in the project.
Cycle through errors with F8 or ⇧F8 (Windows, Linux Shift+F8 )
You can filter problems either by type (‘errors’, ‘warnings’) or text matching.
Change language mode
Keyboard Shortcut: ⌘K M (Windows, Linux Ctrl+K M )
If you want to persist the new language mode for that file type, you can use the Configure File Association for command to associate the current file extension with an installed language.
Customization
There are many things you can do to customize VS Code.
Change your theme
Keyboard Shortcut: ⌘K ⌘T (Windows, Linux Ctrl+K Ctrl+T )
You can install more themes from the VS Code extension Marketplace.
Additionally, you can install and change your File Icon themes.
Keymaps
Are you used to keyboard shortcuts from another editor? You can install a Keymap extension that brings the keyboard shortcuts from your favorite editor to VS Code. Go to Preferences > Migrate Keyboard Shortcuts from. to see the current list on the Marketplace. Some of the more popular ones:
Customize your keyboard shortcuts
Keyboard Shortcut: ⌘K ⌘S (Windows, Linux Ctrl+K Ctrl+S )
You can search for shortcuts and add your own keybindings to the keybindings.json file.
Tune your settings
By default VS Code shows the Settings editor, you can find settings listed below in a search bar, but you can still edit the underlying settings.json file by using the Open Settings (JSON) command or by changing your default settings editor with the workbench.settings.editor setting.
Open User Settings settings.json
Keyboard Shortcut: ⌘, (Windows, Linux Ctrl+, )
Change the font size of various UI elements
Change the zoom level
Tip: You will need to have a font installed that supports font ligatures. FiraCode is a popular font on the VS Code team.
You can also toggle Auto Save from the top-level menu with the File > Auto Save.
Format on paste
Change the size of Tab characters
Whitespace characters are rendered by default in text selection.
Ignore files / folders
Removes these files / folders from your editor window.
Remove these files / folders from search results.
Language specific settings
You can scope the settings that you only want for specific languages by the language identifier. You can find a list of commonly used language IDs in the Language Identifiers reference.
Tip: You can also create language specific settings with the Configure Language Specific Settings command.
Add JSON validation
Enabled by default for many file types. Create your own schema and validation in settings.json
or for a schema defined in your workspace
or a custom schema
See more in the JSON documentation.
Extensions
Keyboard Shortcut: ⇧⌘X (Windows, Linux Ctrl+Shift+X )
Find extensions
Install extensions
In the Extensions view, you can search via the search bar or click the More Actions (. ) button to filter and sort by install count.
Extension recommendations
In the Extensions view, click Show Recommended Extensions in the More Actions (. ) button menu.
Creating my own extension
Are you interested in creating your own extension? You can learn how to do this in the Extension API documentation, specifically check out the documentation on contribution points.
Files and folders
Integrated Terminal
Keyboard Shortcut: ⌃` (Windows, Linux Ctrl+` )
Toggle Sidebar
Keyboard Shortcut: ⌘B (Windows, Linux Ctrl+B )
Toggle Panel
Keyboard Shortcut: ⌘J (Windows, Linux Ctrl+J )
Zen mode
Keyboard Shortcut: ⌘K Z (Windows, Linux Ctrl+K Z )
Enter distraction free Zen mode.
Press Esc twice to exit Zen Mode.
Side by side editing
Keyboard Shortcut: ⌘\ (Windows, Linux Ctrl+\ )
You can also drag and drop editors to create new editor groups and move editors between groups.
Switch between editors
Move to Explorer window
Keyboard Shortcut: ⇧⌘E (Windows, Linux Ctrl+Shift+E )
Create or open a file
Keyboard Shortcut: Ctrl+click ( Cmd+click on macOS)
Close the currently opened folder
Keyboard Shortcut: ⌘K F (Windows, Linux Ctrl+K F )
Navigation history
Navigate entire history: ⌃Tab (Windows, Linux Ctrl+Tab )
File associations
Create language associations for files that aren’t detected correctly. For example, many configuration files with custom file extensions are actually JSON.
Preventing dirty writes
VS Code will show you an error message when you try to save a file that cannot be saved because it has changed on disk. VS Code blocks saving the file to prevent overwriting changes that have been made outside of the editor.
In order to resolve the save conflict, click the Compare action in the error message to open a diff editor that will show you the contents of the file on disk (to the left) compared to the contents in VS Code (on the right):
Use the actions in the editor toolbar to resolve the save conflict. You can either Accept your changes and thereby overwriting any changes on disk, or Revert to the version on disk. Reverting means that your changes will be lost.
Note: The file will remain dirty and cannot be saved until you pick one of the two actions to resolve the conflict.
Editing hacks
Here is a selection of common features for editing code. If the keyboard shortcuts aren’t comfortable for you, consider installing a keymap extension for your old editor.
Multi cursor selection
To add cursors at arbitrary positions, select a position with your mouse and use Alt+Click ( Option+Click on macOS).
To set cursors above or below the current position use:
If you do not want to add all occurrences of the current selection, you can use ⌘D (Windows, Linux Ctrl+D ) instead. This only selects the next occurrence after the one you selected so you can add selections one by one.
Column (box) selection
You can select blocks of text by holding Shift+Alt ( Shift+Option on macOS) while you drag your mouse. A separate cursor will be added to the end of each selected line.
You can also use keyboard shortcuts to trigger column selection.
Vertical rulers
You can 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.
Fast scrolling
Pressing the Alt key enables fast scrolling in the editor and Explorers. By default, fast scrolling uses a 5X speed multiplier but you can control the multiplier with the Editor: Fast Scroll Sensitivity ( editor.fastScrollSensitivity ) setting.
Copy line up / down
The commands Copy Line Up/Down are unbound on Linux because the VS Code default keybindings would conflict with Ubuntu keybindings, see Issue #509. You can still set the commands editor.action.copyLinesUpAction and editor.action.copyLinesDownAction to your own preferred keyboard shortcuts.
Move line up and down
Keyboard Shortcut: ⌥↑ (Windows, Linux Alt+Up ) or ⌥↓ (Windows, Linux Alt+Down )
Shrink / expand selection
Keyboard Shortcut: ⌃⇧⌘← (Windows, Linux Shift+Alt+Left ) or ⌃⇧⌘→ (Windows, Linux Shift+Alt+Right )
You can learn more in the Basic Editing documentation.
Go to Symbol in File
Keyboard Shortcut: ⇧⌘O (Windows, Linux Ctrl+Shift+O )
Go to Symbol in Workspace
Keyboard Shortcut: ⌘T (Windows, Linux Ctrl+T )
Outline view
The Outline view in the File Explorer (default collapsed at the bottom) shows you the symbols of the currently open file.
You can sort by symbol name, category, and position in the file and allows quick navigation to symbol locations.
Navigate to a specific line
Keyboard Shortcut: ⌃G (Windows, Linux Ctrl+G )
Undo cursor position
Keyboard Shortcut: ⌘U (Windows, Linux Ctrl+U )
Trim trailing whitespace
Keyboard Shortcut: ⌘K ⌘X (Windows, Linux Ctrl+K Ctrl+X )
Transform text commands
You can change selected text to uppercase, lowercase, and title case with the Transform commands from the Command Palette.
Code formatting
Currently selected source code: ⌘K ⌘F (Windows, Linux Ctrl+K Ctrl+F )
Code folding
Keyboard Shortcut: ⌥⌘[ (Windows, Linux Ctrl+Shift+[ ) and ⌥⌘] (Windows, Linux Ctrl+Shift+] )
You can also fold/unfold all regions in the editor with Fold All ( ⌘K ⌘0 (Windows, Linux Ctrl+K Ctrl+0 ) ) and Unfold All ( ⌘K ⌘J (Windows, Linux Ctrl+K Ctrl+J ) ).
You can fold all block comments with Fold All Block Comments ( ⌘K ⌘/ (Windows, Linux Ctrl+K Ctrl+/ ) ).
Select current line
Keyboard Shortcut: ⌘L (Windows, Linux Ctrl+L )
Navigate to beginning and end of file
Keyboard Shortcut: ⌘↑ (Windows, Linux Ctrl+Home ) and ⌘↓ (Windows, Linux Ctrl+End )
Open Markdown preview
In a Markdown file, use
Keyboard Shortcut: ⇧⌘V (Windows, Linux Ctrl+Shift+V )
Side by side Markdown edit and preview
In a Markdown file, use
Keyboard Shortcut: ⌘K V (Windows, Linux Ctrl+K V )
The preview and editor will synchronize with your scrolling in either view.
IntelliSense
⌃Space (Windows, Linux Ctrl+Space ) to trigger the Suggestions widget.
You can view available methods, parameter hints, short documentation, etc.
Go to Definition
You can also see the type definition if you press Ctrl ( Cmd on macOS) when you are hovering over the type.
Go to References
Find All References view
Select a symbol then type ⇧⌥F12 (Windows, Linux Shift+Alt+F12 ) to open the References view showing all your file’s symbols in a dedicated view.
Rename Symbol
Search and modify
.eslintrc.json
Install the ESLint extension. Configure your linter however you’d like. Consult the ESLint specification for details on its linting rules and options.
Here is configuration to use ES6.
package.json
See IntelliSense for your package.json file.
Emmet syntax
Snippets
Create custom snippets
File > Preferences > User Snippets (Code > Preferences > User Snippets on macOS), select the language, and create a snippet.
Git integration
Keyboard Shortcut: ⌃⇧G (Windows, Linux Ctrl+Shift+G )
Git integration comes with VS Code «out-of-the-box». You can install other SCM providers from the Extension Marketplace. This section describes the Git integration but much of the UI and gestures are shared by other SCM providers.
Diffs
From the Source Control view, select a file to open the diff.
Alternatively, click the Open Changes button in the top right corner to diff the current open file.
Views
The default view for diffs is the side by side view.
Toggle inline view by clicking the More Actions (. ) button in the top right and selecting Toggle Inline View.
Review pane
Edit pending changes
You can make edits directly in the pending changes of the diff view.
Branches
Easily switch between Git branches via the Status Bar.
Staging
Stage file changes
Hover over the number of files and click the plus button.
Click the minus button to unstage changes.
Stage selected
Stage a portion of a file by selecting that file (using the arrows) and then choosing Stage Selected Ranges from the Command Palette.
Undo last commit
Click the (. ) button and then select Undo Last Commit to undo the previous commit. The changes are added to the Staged Changes section.
See Git output
VS Code makes it easy to see what Git commands are actually running. This is helpful when learning Git or debugging a difficult source control issue.
Gutter indicators
View diff decorations in editor. See documentation for more details.
Resolve merge conflicts
During a merge, go to the Source Control view ( ⌃⇧G (Windows, Linux Ctrl+Shift+G ) ) and make changes in the diff view.
You can resolve merge conflicts with the inline CodeLens which lets you Accept Current Change, Accept Incoming Change, Accept Both Changes, and Compare Changes.
Set VS Code as default merge tool
Set VS Code as default diff tool
Debugging
Configure debugger
From the Run and Debug view ( ⇧⌘D (Windows, Linux Ctrl+Shift+D ) ), select create a launch.json file, which will prompt you to select the environment that matches your project (Node.js, Python, C++, etc). This will generate a launch.json file. Node.js support is built-in and other environments require installing the appropriate language extensions. See the debugging documentation for more details.
Breakpoints and stepping through
Place breakpoints next to the line number. Navigate forward with the Debug widget.
Data inspection
Inspect variables in the Run panels and in the console.
Logpoints
Logpoints act much like breakpoints but instead of halting the debugger when they are hit, they log a message to the console. Logpoints are especially useful for injecting logging while debugging production servers that cannot be modified or paused.
Add a logpoint with the Add Logpoint command in the left editor gutter and it will be displayed as a «diamond» shaped icon. Log messages are plain text but can include expressions to be evaluated within curly braces (‘<>‘).
Task runner
Auto detect tasks
Select Terminal from the top-level menu, run the command Configure Tasks, then select the type of task you’d like to run. This will generate a tasks.json file with content like the following. See the Tasks documentation for more details.
There are occasionally issues with auto generation. Check out the documentation for getting things to work properly.
Run tasks from the Terminal menu
Select Terminal from the top-level menu, run the command Run Task, and select the task you want to run. Terminate the running task by running the command Terminate Task
Define keyboard shortcuts for tasks
For example, to bind Ctrl+H to the Run tests task, add the following:
Run npm scripts as tasks from the Explorer
Portable mode
VS Code has a Portable mode which lets you keep settings and data in the same location as your installation, for example, on a USB drive.
Insiders builds
The Visual Studio Code team uses the Insiders version to test the latest features and bug fixes of VS Code. You can also use the Insiders version by downloading it here.
Format code command for PHP/HTML in Visual Studio Code
Is it possible to get Visual Studio Code to format mixed HTML and PHP code on Windows Visual Studio Code version 0.7.1?
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Update 2021-07-21
The free version of Intelephense supports code formatting with the usual shortcuts ( Alt + Shift + F on Windows and Linux, ⌥⇧F on macOS). Visual Studio Code continues to lack built-in support for PHP code formatting and will direct you to the extension marketplace if you attempt to format PHP without an appropriate extension installed.
Original answer
Visual Studio Code has pretty awesome PHP support. What it lacks is covered by extensions. A quick search reveals at least three (1, 2, and 3) that claim to support PHP formatting.
They mostly seem to use the standard shortcut of Alt + Shift + F on Windows/Linux, with varying shortcuts on Mac. If you’re on Mac, give ⌥⇧F a try.
Visual Studio Code: format is not using indent settings
When using the Format Code command in Visual Studio Code, it is not honoring my indent settings ( «editor.tabSize»: 2 ). It is using a tab size of 4 instead. Any ideas why this is happening?
20 Answers 20
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The number of spaces to use for formatting is taken from a different location. I’m using version 1.0 and this is what I’ve done to fix it (I’m assuming your using spaces instead of tabs):
At the bottom of the editor on the right hand click «Spaces: #»:
Then a menu will appear up top. Select «Indent Using Spaces»:
Finally you can select by how many spaces you want your files to be indented.
The next time you format a file you should be able to get the spacing you configured.
Set also «editor.detectIndentation» to false
For example the Angular CLI generates one with a new project that looks like this
If you’re using a plugin (in my case Vetur, for vue.js), these may set their own tab formatting settings.
For myself, this problem was caused by using the prettier VSCode plugin without having a prettier config file in the workspace.
Disabling the plugin fixed the problem. It could have also probably been fixed by relying on the prettier config.
the settings below solved my issue
Most likely you have some formatting extension installed, e.g. JS-CSS-HTML Formatter.
P.S. Don’t forget to restart Visual Studio Code after editing 🙂
If you came here from google because tab isnt indenting, this can also be because «Tab Moves Focus» is on. It is at the bottom right, and if you have a large enough monitor you may miss it despite it being highlighted.
Click the Green area or Ctrl + M to make it stop. I’m not sure it can be disabled entirely, then again I dont know why a code editor would want to mess with something like indenting.
Also make sure your Workspace Settings aren’t overriding your User Settings. The UI doesn’t make it very obvious which settings you’re editing and «File > Preferences > Settings» defaults to User Settings even though Workspace Settings trump User Settings.
You can also edit Workspace settings directly: /.vscode/settings.json
I sometimes have this same problem. VSCode will just suddenly lose it’s mind and completely ignore any indentation setting I tell it, even though it’s been indenting the same file just fine all day.
I have editor.tabSize set to 2 (as well as editor.formatOnSave set to true). When VSCode messes up a file, I use the options at the bottom of the editor to change indentation type and size, hoping something will work, but VSCode insists on actually using an indent size of 4.
The fix? Restart VSCode. It should come back with the indent status showing something wrong (in my case, 4). For me, I had to change the setting and then save for it to actually make the change, but that’s probably because of my editor.formatOnSave setting.
I haven’t figured out why it happens, but for me it’s usually when I’m editing a nested object in a JS file. It will suddenly do very strange indentation within the object, even though I’ve been working in that file for a while and it’s been indenting just fine.
Format code command for PHP/HTML in Visual Studio Code
Is it possible to get Visual Studio Code to format mixed HTML and PHP code on Windows Visual Studio Code version 0.7.1?
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Update 2021-07-21
The free version of Intelephense supports code formatting with the usual shortcuts ( Alt + Shift + F on Windows and Linux, ⌥⇧F on macOS). Visual Studio Code continues to lack built-in support for PHP code formatting and will direct you to the extension marketplace if you attempt to format PHP without an appropriate extension installed.
Original answer
Visual Studio Code has pretty awesome PHP support. What it lacks is covered by extensions. A quick search reveals at least three (1, 2, and 3) that claim to support PHP formatting.
They mostly seem to use the standard shortcut of Alt + Shift + F on Windows/Linux, with varying shortcuts on Mac. If you’re on Mac, give ⌥⇧F a try.
Java formatting and linting
Language Support for Java™ by Red Hat also provides formatting settings. You can export an Eclipse formatter file and then use it for your project in VS Code.
In addition, there are also the Checkstyle for Java and SonarLint extensions, which provide features for live linting and code analysis.
Formatter
You can use Format Document command to format a Java file. If you didn’t specify a formatter profile before, the Java file will be formatted using default settings.
Applying formatter settings
You can easily apply formatter settings from an existing formatter profile in Eclipse scheme. For example, if you want to apply Google Style for your Java project, then you can set the following property in settings.json :
The property can be set to a URL or a local file path. If the formatter XML file contains more than one profile, you can specify the profile name:
After setting the formatter profile, the Format Document command will use the specific profile to format your Java files.
Editing formatter settings
The Extension Pack for Java provides an editor to help users edit an existing formatter profile. You can open the editor with the command Java: Open Java Formatter Settings with Preview. In the editor, you can change the formatter settings and preview the effects. After saving the current editor, the changes will be saved to the formatter profile.
When editing settings in the editor, you can preview the changes’ effects in the right Preview panel.
You can also undo and redo changes.
SonarLint
SonarLint is an easy-to-use extension that helps you find and fix bugs and security issues as you code. The extension runs in the background and, just like a spell checker, highlights source code issues that pose a quality or security concern. The extension not only tells you what the issue is but also provides in-context guidance on why it’s harmful and how to fix it, with examples. The extension supports over 500+ Java rules and includes several Quick Fixes to automatically fix certain quality issues.
Code analysis on the fly
Issues are highlighted directly in the editor with hovers to provide detailed explanations.
Issues found in the opened file can also be reviewed through the Problems panel of VS Code. When applicable, secondary code locations are mentioned so you can understand where the issue originates from (for example, the code path that led to a bug).
Rule documentation and remediation guidance
For any issues detected, SonarLint provides full documentation about the rule that was violated, and the best coding practice it relates to. This allows you to understand why an issue is raised, and how to fix it.
Enabling more quality and security rules
By default, SonarLint provides a wide array of rules to detect bugs and vulnerabilities. More checks can be enabled through the SonarLint Rules view.
Checkstyle
With the Checkstyle for Java extension, you can use either existing checkstyle configurations (Google’s or Sun’s Check) or your own customized files for your project. When editing a Java file, the extension will check the file format and provide Quick Fixes if possible on the fly.
Set Checkstyle configuration file using the Checkstyle: Set the Checkstyle Configuration File command and selecting the Checkstyle file from the dropdown.
The Checkstyle for Java extension supports live linting.
And batch check.
The Problems panel will open when you click the Checkstyle status icon in the Status bar.
Set Checkstyle configuration file
You can also trigger the command Checkstyle: Set Checkstyle Configuration File to choose the configuration file in the File Explorer. The extension looks for a checkstyle.xml file in your workspace to make Checkstyle configuration easier. You will also see the two built-in configurations:
The command Checkstyle: Set the Checkstyle Configuration detects potential Checkstyle configuration files and lists them. You can also provide a configuration file by directly writing a URL in the input box.
You can also set the Checkstyle version by using the command Checkstyle: Set the Checkstyle Version.
The command will:
In addition, you can also bring any 3rd-party modules for Checkstyle by configuring its path. For example, after using the configuration below, you can add or to checkstyle.xml to use those checks.
Check the style and fix the violations
When editing a Java file, the extension will check the file format and provide Quick Fixes if possible. You can click the lightbulb button in the editor to show the available Quick Fixes.
Возможности редактора кода
Редактор Visual Studio предоставляет множество возможностей, облегчающих написание кода и текста, а также управление им. Используя структуру, вы можете разворачивать и сворачивать различные блоки кода. Получить дополнительные сведения о коде можно с помощью технологии IntelliSense, окна Обозреватель объектов и иерархии вызовов. Для поиска в коде можно использовать такие функции, как Перейти, Перейти к определению и Найти все ссылки. Вставлять блоки кода можно с помощью фрагментов кода. Код также можно создавать с помощью функций, таких как Создание в результате использования. Если вы ранее не работали в редакторе Visual Studio, см. статью со сведениями об использовании редактора кода.
Этот раздел относится к Visual Studio в Windows. Информацию о Visual Studio для Mac см. в статье Редактор исходного кода (Visual Studio для Mac).
Код можно просматривать различными способами. По умолчанию в обозревателе решений код упорядочен по файлам. Чтобы просмотреть код, упорядоченный по классам, можно выбрать вкладку Представление классов в нижней части окна.
Можно выполнять поиск и замену текста в одном или нескольких файлах. Дополнительные сведения см. в статье Поиск и замена текста. Регулярные выражения платформы используются для поиска и замены текста. Дополнительные сведения см. в статье Использование регулярных выражений в Visual Studio.
Разные языки Visual Studio предоставляют разные наборы функций, а в некоторых случаях одни и те же функции ведут себя по-разному в разных языках. Многие из этих отличий указаны в описаниях функций. Дополнительные сведения можно найти в разделах, посвященных конкретным языкам Visual Studio.
Возможности редактора
Функция | Описание |
---|---|
Цветовая раскраска синтаксических конструкций | Некоторые элементы синтаксиса кода и файлов разметки для наглядности выделяются разными цветами. Например, ключевые слова (такие как using в C# и Imports в Visual Basic) выделены одним цветом, а типы (такие как Console и Uri ) — другим. Другие элементы синтаксиса (например, строковые литералы и комментарии) также выделены цветом. Язык C++ использует цвета для различения типов, перечислений и макросов среди других токенов. |
Вы можете узнать, какой цвет задан по умолчанию для каждого типа, и изменить цвет для любого элемента синтаксиса в диалоговом окне Fonts and Colors, Environment, Options Dialog Box, которое можно открыть с помощью меню Сервис.
Дополнительные возможности редактирования
В меню Правка>Дополнительно на панели инструментов есть набор дополнительных функций. Не все они доступны для каждого типа файлов кода.
Перемещение по коду и поиск
Перемещаться по редактору кода можно несколькими способами, включая переход назад и вперед к точкам вставки, просмотр определения типа или члена и переход к определенному методу с помощью панели навигации. Дополнительные сведения см. в статье Навигация по коду.
Поиск ссылок в базе коде
Чтобы найти, где именно в базе кода используются ссылки на элементы кода, можно использовать команду Найти все ссылки или нажать SHIFT+F12. Кроме того, когда вы щелкаете тип или член, функция выделения ссылок автоматически выделяет все ссылки на него. Дополнительные сведения см. в разделе Поиск ссылок в коде.
Создание, исправление или рефакторинг кода
Visual Studio помогает создавать, исправлять код и выполнять его рефакторинг самыми разными способами.
Вы можете использовать фрагменты кода для вставки шаблона, такого как блок switch или объявление enum.
Вы можете использовать быстрые действия для создания кода, например классов и свойств, или для введения локальной переменной. Кроме того, быстрые действия можно использовать для улучшения кода, например для удаления ненужных приведений и переменных либо для добавления проверок значений NULL перед обращением к переменным.
Вы можете выполнять рефакторинг кода, например чтобы переименовывать переменные, изменять порядок параметров метода или синхронизировать тип с его именем файла.
Настройка редактора
Вы можете использовать свои параметры Visual Studio совместно с другим разработчиком, привести параметры в соответствие со стандартом или вернуться к настройкам, заданным по умолчанию в Visual Studio, с помощью команды Мастер импорта и экспорта параметров в меню Сервис. В мастере импорта и экспорта параметров можно изменить выбранные общие параметры, а также зависящие от языка и проекта параметры.
Чтобы определить новые или переопределить существующие сочетания клавиш, выберите Сервис>Параметры>Среда>Клавиатура. Дополнительные сведения о сочетаниях клавиш см. в статье Сочетания клавиш по умолчанию в Visual Studio.
Параметры редактора для JavaScript см. в статье о параметрах редактора JavaScript.
Visual studio code CSS indentation and formatting
It’s working fine with JavaScript but strangely not with CSS.
11 Answers 11
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
or
i think both this extension uses js-beautify internally
Wasted an hour finding the best option.
Just putting it together, for easy reading and choosing one them.
Notes:
Options:
To format:
Press Alt + Shift + F in VS Code, after installing Prettier.
Beautify / Format Java code in Visual Studio Code
I have tried some proposals on here and here, but none of them works. How do you accomplish it for Java code or is there a way for general? En passant, I’ve install XML formatter in order that it may work, but not.
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Formatting a JAVA Document in VSCode requires one to follow the below steps:
Install the plugin: Language Support for Java(TM) by Red Hat from the Extensions window in VSCode.
Post Installation, from the required page with JAVA code
The Java Document should be now properly formatted.
If you wish to bind Alt + Shift + F to format your JAVA Document,
then you can add the below configuration to your settings.json by:
Visual Studio Code doesn’t format C# code
I created a new file, set the C# language, and wrote some code. Then I pressed Ctrl + Shift + F (or F1 → Format Document). And got I the error
Sorry, but there is no formatter for ‘csharp’-files installed.
Also, I installed C# Extension, but it didn’t help. The Visual Studio Code version is 1.18.0.
18 Answers 18
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you have prettier as the default formatter as I do, you should do this:
Then click to «open settings (JSON)»:
This is where you should paste the below snippet.
This is my config:
For you to apply this configuration you need c# extension.
This works for me.
Note: If it is true then clear the checkbox and set it to true again. After that, you must restart Visual Studio Code.
Menu File → Preferences → Settings →
3/4/5 unity engine projects on mac
Browse the Visual Studio Code extension library, and make sure you’ve got the C# extension installed ms-dotnettools.csharp
Restart Visual Studio Code. It should now make code auto-format when you complete the line with a semicolon, or when you close the outer brace of a scope.
Note: this is a global setting for the editor, so it may enable auto-formatting for other languages and not just C#.
This was tested on Visual Studio Code version 1.43.1.
Is there a format code shortcut for Visual Studio?
12 Answers 12
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Visual Studio with C# key bindings
To answer the specific question, in C# you are likely to be using the C# keyboard mapping scheme, which will use these hotkeys by default:
You can change these in menu Tools → Options → Environment → Keyboard (either by selecting a different «keyboard mapping scheme», or binding individual keys to the commands «Edit.FormatDocument» and «Edit.FormatSelection»).
If you have not chosen to use the C# keyboard mapping scheme, then you may find the key shortcuts are different. For example, if you are not using the C# bindings, the keys are likely to be:
Ctrl + K + D (Entire document)
Ctrl + K + F (Selection only)
(Please do not edit this answer to change the key bindings above to what your system has!)
Code formatting in Visual Studio Code is not working on C# code
All the answers provided in this question are not working with C# code.
I just copied my controller file and opened it in Visual Studio Code. I tried to format code with Shift + Alt + F (both right and left shifts in windows)
But it didn’t work.
Is there a solution for this?
The same shortcut is working for HTML and JavaScript files.
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
For C# you need to
In my case the problem was related with the code formatting extension.
I was using C# for «Visual Studio Code (powered by OmniSharp)» (ms-vscode.csharp) extension for formatting. However, after a while the «format document» context menu has gone missing. And the key combination for formatting «Shift+Alt+F» stopped working.
After some research I have found that there is a new extension called «C# FixFormat» (Leopotam.csharpfixformat) for formatting C# documents which says in their description: «there is bug in omnisharp and they are fixing the issue temporarily«.
After installing «C# FixFormat» extension I can now format documents again.
C++ EditorConfig formatting conventions
The Visual Studio C++ formatter has a rich set of configurable settings that can be applied globally. To set C++ formatting settings for a specific workspace, use clangformat or EditorConfig. Both Visual Studio and Visual Studio Code have built-in EditorConfig support for each of the global Visual Studio C++ formatting settings, with the EditorConfig settings taking precedence. This means you can add EditorConfig files to your workspace to configure C++ formatting on a more granular level and enforce consistent code style for everyone contributing to the project.
C++ formatting conventions
The rest of this document lists all the EditorConfig C++ formatting settings supported by Visual Studio and VS Code.
Indentation settings
Indent braces
Indent each line relatively to
Within parentheses, align new lines when I type them
In existing code, do not use the setting for alignment of new lines within parentheses
Indent case contents
Indent case labels
Indent braces following a case statement
Indent braces of lambdas used as parameters
Position of goto labels
Position of preprocessor directives
Indent access specifiers
Indent namespace contents
Preserve indentation of comments
Newline settings
Position of open braces for namespaces
Position of open braces for types
Position of open braces for functions
Position of open braces for control blocks
Position of open braces for lambdas
Place scope braces on separate lines
For empty types, move closing braces to the same line as opening braces
For empty function bodies, move closing braces to the same line as opening braces
Place ‘catch’ and similar keywords on a new line
Place ‘else’ on a new line
Place ‘while’ in a do-while loop on a new line
Spacing settings
Spacing between function names and opening parentheses of argument lists
Insert space within parentheses of an argument list
Insert space between parentheses when argument list is empty
Insert space between keyword and opening parenthesis in control flow statements
Insert space within parentheses of a control statement
Insert space before opening parenthesis of lambda argument lists
Insert space within parentheses of a C-style cast
Insert space after closing parenthesis of C-style cast
Insert space within parentheses of a parenthesized expression
Insert space before opening brace of blocks
Insert space between empty braces
Insert space before opening brace of uniform initialization and initializer lists
Insert space within braces of uniform initialization and initializer lists
Preserve spaces inside uniform initialization and initializer lists
Insert space before opening square brackets
Insert space within square bracket
Insert space before empty square brackets
Insert space between empty square brackets
Group square brackets for multi-dimensional arrays together
Insert space within square brackets for lambdas
SpaceBetweenEmptyLambdaBrackets
Insert space before commas
Insert space after commas
Remove spaces before and after member operators
Insert space before colon for base in type declarations
Insert space before colon for constructors
Remove space before semicolons
Insert space after semicolons
Remove spaces between unary operators and their operands
Spacing for binary operators
Spacing for assignment operators
Pointer/reference alignment
Spacing for conditional operators
Wrapping options
Wrapping options for blocks
How to indent/format a selection of code in Visual Studio Code?
I want to indent a specific section of code in Visual Studio Code.
I read How do you format code in Visual Studio Code? that gives shortcuts to indent the whole code, but it doesn’t work when selecting a specific section of code.
I tried Ctrl + Shift + F after selecting some line in my code, but the whole file is indented. I’m on Windows with Visual Studio Code Insider 1.8.0. How can I do it?
14 Answers 14
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I want to indent a specific section of code in Visual Studio Code:
If you want to format a section (instead of indent it):
And of course for auto indentation and formatting, following the language you’re using, you can see which good extensions do the good job, and which formatters to install or which parameters settings to enable or set for each language and its available tools. Just make sure to read well the documentation of the extension, to install and set all what it need.
Up to now the indentation problem bothers me with Python when copy pasting a block of code. If that’s the case, here is how you solve that: Visual Studio Code indentation for Python
Code Formatting in Visual Studio
Is there some combination of keys or a menu option that I can use to automatically format my code in Visual Studio?
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You could try the CodeMaid extension to Visual Studio.
This does code cleaning with the following steps:
Remove unused using statements
Sort using statements
Add unspecified access modifiers
Add blank line padding
Remove blank lines adjacent to braces
Run Visual Studio formatting
Remove consecutive blank lines
Remove end of line whitespace
Update endregion tags
So you get Visual Studio’s built-in reformatting plus lots of other tidying in one go. I expect there are other tools that do the same thing. I’ve been using CodeMaid for a while now and it’s both fast and reliable.
I guess you mean to format and indent the document nicely.
ctrl +E,D
If you really meant what JaredPar and Glenn are meaning you could also think about installing the PowerCommands for Visual Studio.
Also you should know that the keystroke of JaredPar and Glenn are not always working. Depending on what you selected at the first start of Visual Studio (are you a C#, VB, Web or Generic programmer) the keystrokes are slightly different.
If you selected C# developer the answer of Glenn and JaredPar works. If you selected generic or C++ developer only JaredPar answer works. If you took another role than maybe none of these keystrokes works and you have to check your keystroke through the menu at the position JaredPar mentioned.
How to indent/format a selection of code in Visual Studio Code?
I want to indent a specific section of code in Visual Studio Code.
I read How do you format code in Visual Studio Code? that gives shortcuts to indent the whole code, but it doesn’t work when selecting a specific section of code.
I tried Ctrl + Shift + F after selecting some line in my code, but the whole file is indented. I’m on Windows with Visual Studio Code Insider 1.8.0. How can I do it?
14 Answers 14
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I want to indent a specific section of code in Visual Studio Code:
If you want to format a section (instead of indent it):
And of course for auto indentation and formatting, following the language you’re using, you can see which good extensions do the good job, and which formatters to install or which parameters settings to enable or set for each language and its available tools. Just make sure to read well the documentation of the extension, to install and set all what it need.
Up to now the indentation problem bothers me with Python when copy pasting a block of code. If that’s the case, here is how you solve that: Visual Studio Code indentation for Python
How to change code formatting in Visual Studio Code
Hi I’m using VS Code for TypeScript and JavaScript. Standart autoformat create code like this
but I don’t like this :), how to set autoformat as
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
This is currently not possible with VsCode, but there is an issue tracking the problem and here’s the actual code fix.
Keep in mind that this is from the development branch, so the behavior and settings may change, but I believe the settings you will want are:
javascript.format.placeOpenBraceOnNewLineForControlBlocks and/or javascript.format.placeOpenBraceOnNewLineForFunctions
This feature should make it into an official release shortly, but if you want the try out bleeding edge features you can always build VsCode from the source.
Visual Studio Code formatting for «< >«
I’m on Ubuntu. C++ in Visual Studio Code automatically lints like
Instead I want to do :
How do I do that?
I’ve already installed the C/C++ extension from the marketplace.
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
base on @Chris Drew’s answer
If you want more:
I generally have my own way of formatting almost everything 🙂 so i prefer the most flexible way to achieve this. VS code is by far the most flexible editor as far as c++ formatting is concerned and also «easy».
This is what you should do to get custom formatting.
Here is my file for your reference.
The formatting you are interested in especially is «AfterControlStatement: false»
Using MacOS for example, an ideal method of configuring clang-format for VS Code is to first install clang-format with Homebrew:
Then, use it to export the full style settings to
Then, perform the following in VS Code:
This sets the formatter to the clang-formatter installed with Homebrew, which will automatically pull your style settings from the
/.clang-format file you just created. This way, you can change every parameter in the style as desired and not just a subset of these.
csharpier
CSharpier Formatter for Visual Studio Code
CSharpier is an opinionated code formatter for c#. It uses Roslyn to parse your code and re-prints it using its own rules. The printing process was ported from prettier but has evolved over time.
Installation
Install through VS Code extensions. Search for CSharpier
Can also be installed in VS Code: Launch VS Code Quick Open (Ctrl+P), paste the following command, and press enter.
Usage
Keyboard Shortcuts
Visual Studio Code provides default keyboard shortcuts for code formatting. You can learn about these for each platform in the VS Code documentation.
If you don’t like the defaults, you can rebind editor.action.formatDocument and editor.action.formatSelection in the keyboard shortcuts menu of vscode.
Format On Save
Respects editor.formatOnSave setting.
Found in the settings at Text Editor | Formatting | Format on Save
You can turn on format-on-save on a per-language basis by scoping the setting:
Как форматировать код в Visual Studio Code (VSCode)
что эквивалентно Ctrl + K + F и Ctrl + K + D в Windows в Visual Studio для форматирования или» украшения » кода в редакторе кода Visual Studio?
30 ответов:
форматирование кода доступно в VS Code с помощью следующих ярлыков:
кроме того, вы можете найти ярлык, а также другие ярлыки, через поиск функциональность, предоставляемая в редакторе с Ctrl + Shift + P (или команда + Shift + P на Mac), а затем поиск документ в формате.
Контекстное Форматирование Кода:
вы также можете настроить этот ярлык через настройки, если это необходимо.
Форматирование Кода В То Время Как Сохранение файла:
Visual Studio code позволяет пользователю настраивать параметры по умолчанию.
Если вы хотите автоматически форматировать содержимое при сохранении, добавьте этот фрагмент кода ниже в настройках рабочего пространства visual studio code.
Примечание: теперь вы можете автоматически форматировать файлы typescript проверить мое обновление
или Visual Studio как:
правильная комбинация клавиш shift + alt + f
также обратите внимание, что на сегодняшний день форматирование доступно для этих языков:
VS Code 1.6.1 поддерживает «Формат При Сохранении » который будет автоматически подбирать соответствующие установленные расширения форматирования и форматировать весь документ на каждом сохранении.
включить «формат при сохранении», установив
и есть доступные сочетания клавиш (VS Code 1.7 и выше):
форматировать весь документ: Shift + Alt + F
только выбор формата: Ctrl K + Ctrl F
для других языков может потребоваться установить определенный языковой пакет.
на ubuntu это Ctrl + Shift + Я
Indent/format code in Visual Studio code on MAC
i’m trying to indent my code in visual studio code. I searched and i found that ctrl + F + K should be work, but it doesn’t. I tried cmd + k + f too, but it still not working. I hope you can help me!
11 Answers 11
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Updated December 21, 2017: as pointed out by Fabio, on mac it should be: ⌘ + ]
On Windows: indent control is ctrl + ]
Also, the Visual Studio Code team provided those handy shortcut pdfs:
Another helpful command to achieve this might be: shift + option + f which is auto format.
The shortcut is: Alt + Shift + F
The shortcut to format code on Visual Studio for Mac Community Edition is Ctrl + i
The shortcut to align code in MAC is : Option/ALT + Shift + F.
(edited on 4th May 2022: the answer below still remains the same, in version 1.66.2, March 2022)
For visual studio code version 1.36.1 (2019)
To auto-format the selection, use ⌘K ⌘F (the trick is that this is to be done in sequence, ⌘K first, followed by ⌘F).
To just indent (shift right) without auto-formatting, i.e., blindly indent, use ⌘]
As indicated in Visual Studio Code’s Keyboard Shortcuts (⌘K ⌘S, or from the menu as shown below)
Format html code in Visual Studio Code such that attributes are on separate lines?
There seems to be a lack of formatting settings for vscode. I want to be able to format html such that my html shows up as:
This is one functionality that I’d really love to have!
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
VSCode added a way to do this now. You can edit your settings.json (ctrl+shift+p) and then add the following for the desired effect:
force-aligned will also add indents to align it with the attribute on the line where tag was opened.
Visit this link for more details or updates.
My extended html was being limited by the «Prettier: Print width» setting, I thought I’d put a random value as 0, but then all the tags start breaking the attributes. So he put 10,000. This solved my problem.
There are differnt «formatter» extensions, but one I found does a decent job of this exact formatting that you are looking for. It’s called «vscode-tidyhtml«.
It should format HTML so that attributes are on different lines. I am not sure if it works well for other file types.
Is there a format code shortcut for Visual Studio?
12 Answers 12
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Visual Studio with C# key bindings
To answer the specific question, in C# you are likely to be using the C# keyboard mapping scheme, which will use these hotkeys by default:
You can change these in menu Tools → Options → Environment → Keyboard (either by selecting a different «keyboard mapping scheme», or binding individual keys to the commands «Edit.FormatDocument» and «Edit.FormatSelection»).
If you have not chosen to use the C# keyboard mapping scheme, then you may find the key shortcuts are different. For example, if you are not using the C# bindings, the keys are likely to be:
Ctrl + K + D (Entire document)
Ctrl + K + F (Selection only)
(Please do not edit this answer to change the key bindings above to what your system has!)
Beautify / Format Java code in Visual Studio Code
I have tried some proposals on here and here, but none of them works. How do you accomplish it for Java code or is there a way for general? En passant, I’ve install XML formatter in order that it may work, but not.
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Formatting a JAVA Document in VSCode requires one to follow the below steps:
Install the plugin: Language Support for Java(TM) by Red Hat from the Extensions window in VSCode.
Post Installation, from the required page with JAVA code
The Java Document should be now properly formatted.
If you wish to bind Alt + Shift + F to format your JAVA Document,
then you can add the below configuration to your settings.json by:
How do I format all files in a Visual Studio Code project?
Is there a way to format all files in a project without formatting each one individually?
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Use the extension called ”Format Files”. Here are the steps:
This works for me
Install prettier:
Add following script in package.json:
The simplest solution that I have found is as below.
I was out of luck finding an extension that was doing this the way I was expecting it so I made one. I suggest you take a look at the extension I just made :
It might still have some issues, feel free to report them or to contribute.
You can use the extension Command on All Files
Add this to your settings.json
From the command palette select command Apply 1 or more commands to all files in the Workspace and select Format File from the Quickpick list. Wait till you see an information message (lower right) that all files have been processed.
I do a simply trick:
As @herrbischoff said, there is currently no way to format all files in a project.
However it would be a useful feature.
What it can do is format all unsaved files by having auto-save and auto-format on.
Otherwise you would need a shell script or an extension or some other extern program (like a tslint checker which can auto-correct errors) which is capable of doing this.
Had problems with this myself and it sucks to open all files by hand
There is currently no way to do that nor does it sound like a particularly useful feature to have. Or put another way: it would be a useful feature if you could completely trust it, which you can’t.
You would have to put a lot of faith into the auto-formatting logic of the used languages to not screw up and possibly introduce errors. You would need to review the changes manually anyway, so this approach should not result in measurable productivity gains.
If you’re working with a seriously f’ed up code base and don’t care about possible problems, I would suggest running a simple shell command with the respective languages’ CLI formatter. Example for C++ code, using clang-format:
This command will find all cpp files recursively and will run them through the formatter with default settings.
The process is essentially the same for any language, for example JavaScript (with js-beautify):
Just make sure you review whatever comes out. Also, it may very well be possible to script this command into VScode — or just run it in the built-in terminal.
Источники:
- http://stackoverflow.com/questions/35984564/how-to-format-code-in-visual-studio-code-on-windows
- http://www.digitalocean.com/community/tutorials/how-to-format-code-with-prettier-in-visual-studio-code
- http://stackoverflow.com/questions/30064480/how-do-you-change-the-formatting-options-in-visual-studio-code
- http://code.visualstudio.com/docs/cpp/cpp-ide
- http://docs.microsoft.com/en-us/visualstudio/ide/code-styles-and-code-cleanup?view=vs-2022
- http://docs.microsoft.com/ru-ru/visualstudio/ide/code-styles-and-code-cleanup?view=vs-2019
- http://marketplace.visualstudio.com/items?itemName=lonefy.vscode-JS-CSS-HTML-formatter
- http://medium.com/zurassic/visual-studio-code-formatting-setup-9f40a95699ce
- http://docs.microsoft.com/en-us/answers/questions/550115/automatic-format-code-in-visual-studio.html
- http://stackoverflow.com/questions/44987378/how-to-format-file-in-visual-studio-code-hotkeys
- http://marketplace.visualstudio.com/items?itemName=vs-publisher-599079.CodeFormatter
- http://marketplace.visualstudio.com/items?itemName=rohit-gohri.format-code-action
- http://code.visualstudio.com/Docs/editor/codebasics?source=post_page—————————
- http://stackoverflow.com/questions/4942113/is-there-a-format-code-shortcut-for-visual-studio
- http://stackoverflow.com/questions/32236030/format-code-command-for-php-html-in-visual-studio-code
- http://stackoverflow.com/questions/49500433/auto-format-c-sharp-code-in-visual-studio-code
- http://stackoverflow.com/questions/752600/visual-studio-code-formatter?lq=1
- http://stackoverflow.com/questions/47352611/visual-studio-code-doesnt-format-c-sharp-code?lq=1
- http://docs.microsoft.com/en-us/visualstudio/python/formatting-python-code?view=vs-2022
- http://stackoverflow.com/questions/45823734/visual-studio-code-formatting-for?lq=1
- http://stackoverflow.com/questions/4942113/is-there-a-format-code-shortcut-for-visual-studio?rq=1
- http://code.visualstudio.com/docs/getstarted/tips-and-tricks?ref=hackernoon.com
- http://stackoverflow.com/questions/45823734/visual-studio-code-formatting-for
- http://stackoverflow.com/questions/32236030/format-code-command-for-php-html-in-visual-studio-code/32239293
- http://code.visualstudio.com/docs/python/editing
- http://stackoverflow.com/questions/52188779/how-can-i-modify-the-code-formatting-for-c-in-visual-studio-code
- http://code.visualstudio.com/docs/getstarted/keybindings
- http://stackoverflow.com/questions/9197577/code-formatting-in-visual-studio
- http://github.com/microsoft/vscode-docs/blob/main/docs/getstarted/keybindings.md
- http://stackoverflow.com/questions/47352611/visual-studio-code-doesnt-format-c-sharp-code
- http://stackoverflow.com/questions/33560205/format-html-code-in-visual-studio-code-such-that-attributes-are-on-separate-line
- http://docs.microsoft.com/ru-RU/visualstudio/ide/code-styles-and-code-cleanup?view=vs-2022
- http://stackoverflow.com/questions/32236030/format-code-command-for-php-html-in-visual-studio-code/58832322
- http://stackoverflow.com/questions/49500433/auto-format-c-sharp-code-in-visual-studio-code/49501258
- http://askdev.ru/q/kak-formatirovat-kod-v-visual-studio-code-vscode-644/
- http://stackoverflow.com/questions/32236030/format-code-command-for-php-html-in-visual-studio-code/67275235
- http://code.visualstudio.com/blogs/2016/11/15/formatters-best-practices
- http://docs.microsoft.com/en-us/visualstudio/python/formatting-python-code?view=vs-2019
- http://stackoverflow.com/questions/6167648/visual-studio-reformat-code-document
- http://stackoverflow.com/questions/5755942/how-do-you-auto-format-code-in-visual-studio?page=2&tab=votes
- http://code.visualstudio.com/docs/getstarted/tips-and-tricks?s=04
- http://stackoverflow.com/questions/32236030/format-code-command-for-php-html-in-visual-studio-code/61042286
- http://stackoverflow.com/questions/36251820/visual-studio-code-format-is-not-using-indent-settings
- http://stackoverflow.com/questions/32236030/format-code-command-for-php-html-in-visual-studio-code/71649032
- http://code.visualstudio.com/docs/java/java-linting
- http://docs.microsoft.com/ru-RU/visualstudio/ide/writing-code-in-the-code-and-text-editor?view=vs-2022
- http://stackoverflow.com/questions/37739375/visual-studio-code-css-indentation-and-formatting
- http://stackoverflow.com/questions/42940091/beautify-format-java-code-in-visual-studio-code
- http://stackoverflow.com/questions/47352611/visual-studio-code-doesnt-format-c-sharp-code/59154222
- http://stackoverflow.com/questions/4942113/is-there-a-format-code-shortcut-for-visual-studio/4942122
- http://stackoverflow.com/questions/32709289/code-formatting-in-visual-studio-code-is-not-working-on-c-sharp-code
- http://docs.microsoft.com/en-us/visualstudio/ide/cpp-editorconfig-properties?view=vs-2019
- http://stackoverflow.com/questions/40492960/how-to-indent-format-a-selection-of-code-in-visual-studio-code
- http://stackoverflow.com/questions/9197577/code-formatting-in-visual-studio/48074397
- http://stackoverflow.com/questions/40492960/how-to-indent-format-a-selection-of-code-in-visual-studio-code/40497671
- http://stackoverflow.com/questions/35939427/how-to-change-code-formatting-in-visual-studio-code
- http://stackoverflow.com/questions/45823734/visual-studio-code-formatting-for/46064866
- http://marketplace.visualstudio.com/items?itemName=csharpier.csharpier-vscode
- http://codengineering.net/q/how-do-you-format-code-in-visual-studio-code-vscode-27090
- http://stackoverflow.com/questions/35149275/indent-format-code-in-visual-studio-code-on-mac
- http://stackoverflow.com/questions/33560205/format-html-code-in-visual-studio-code-such-that-attributes-are-on-separate-line/43508504
- http://stackoverflow.com/questions/4942113/is-there-a-format-code-shortcut-for-visual-studio/66063689
- http://stackoverflow.com/questions/42940091/beautify-format-java-code-in-visual-studio-code?rq=1
- http://stackoverflow.com/questions/43666270/how-do-i-format-all-files-in-a-visual-studio-code-project
- Visual studio code download
- Visual studio code github