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

Как сделать код красивым в visual studio

  • автор:

Конфигурирование стиля кода в Visual Studio 2017


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

Visual Studio 2017 обеспечивает соблюдение стиля написания кода и поддержку EditorConfig. Новая версия включает в себя больше правил для code style и позволяет разработчикам настраивать стиль кода через EditorConfig.

Что такое EditorConfig?

EditorConfig — это формат файла с открытым исходным кодом, который помогает разработчикам настраивать и применять правила форматирования и соглашения о стиле написания кода для получения более читаемых кодовых баз (codebases). Файлы EditorConfig легко включаются в систему управления версиями и применяются на уровне репозитория и проекта. Соглашения EditorConfig переопределяют их эквиваленты в ваших личных настройках, так что соглашения из кодовой базы имеют приоритет над индивидуальным разработчиком.

Простота и универсальность редактора EditorConfig делают его привлекательным выбором для командных параметров code style в Visual Studio (и за его пределами). Microsoft вместе с сообществом EditorConfig, добавили его поддержку в Visual Studio и продолжают расширять формат, включая в него параметры code style характерные для .NET среды.

EditorConfig и .NET Code Style

Начало работы

Roslyn в полной мере использует стиль, описанный в .NET Foundation Coding Guidelines. Настройка правил в файле EditorConfig позволит разработчикам отслеживать нарушения своих правил кодирования по мере их ввода, а не в процессе code review.

Чтобы определить стиль кода и параметры форматирования для всего репозитория, просто добавьте файл .editorconfig в каталог верхнего уровня. Чтобы установить эти правила в качестве «корневых» параметров, добавьте следующее в .editorconfig (вы можете сделать это в своем редакторе / IDE по выбору):

# top-most EditorConfig file
root = true

Параметры EditorConfig применяются сверху вниз с переопределениями, то есть вы описываете общие правила наверху и переопределяете их дальше вниз в своем дереве каталогов по мере необходимости. В репозитории Roslyn файлы в каталоге Compilers не используют var, поэтому мы можем просто создать другой файл .editorconfig, который содержит различные настройки для предпочтений var, и эти правила будут применяться только к файлам в этом каталоге. Обратите внимание, что когда мы создаем этот EditorConfig файл в каталоге Compilers, то нам не нужно добавлять root = true (это позволит наследовать правила из родительского каталога или, в данном случае, из каталога Roslyn верхнего уровня).

Правила форматирования кода
Правила стиля кода

После совместной работы с сообществом EditorConfig формат файла был расширен, чтобы поддерживать стиль кода .NET. Также расширился набор конвенций по кодированию, которые могут быть сконфигурированы и применены для включения таких правил, как предпочтение collection initializers, expression-bodied members, C#7 pattern matching и многое другое!

Давайте рассмотрим пример того, как могут быть определены соглашения о кодировании:

  • Настройки предпочтений могут быть либо true(означать, «использовать это правило»), либо false (что означает «не использовать это правило»).
  • Уровень выполнения одинаковый для всего анализа кода на основе Roslyn и может быть от наименьшей серьезности до самого серьезного: none, suggestion, warning или error.

Если вам нужно переосмыслить различные уровни серьезности и то, что они делают:

Совет: серые точки, которые указывают на предложение, довольно серые. Чтобы разнообразить вашу жизнь, попробуйте изменить их на приятный розовый. Для этого перейдите в меню Tools > Options > Environment > Fonts and Colors > Suggestion ellipses (…) и задайте для параметра следующий настраиваемый цвет (R: 255, G: 136, B: 196):

Опыт работы в Visual Studio

Когда вы добавляете файл EditorConfig к существующему репозиторию или проекту, файлы не проверяются автоматически, чтобы соответствовать вашим соглашениям. Когда вы добавляете или редактируете EditorConfig файл, чтобы применить новые настройки, вы должны закрыть и открыть все открытые файлы, которые у вас есть. Чтобы весь документ придерживался правил форматирования кода, определенных в ваших настройках, вы можете использовать Format Document (Ctrl + K, D). Эта проверка не изменяет код, но вы можете использовать меню быстрых действий (Ctrl +.), чтобы применить исправление стиля кода ко всем вхождениям в документе/проекте/решении.

Совет: Чтобы проверить, что в вашем документе используются пробелы или табуляции, включите Edit > Advanced > View White Space.

Но как узнать, применяется ли файл EditorConfig к вашему документу? Вы можете взглянуть на нижнюю строку состояния Visual Studio и увидеть это сообщение:

Обратите внимание, что это означает, что EditorConfig файлы переопределяют любые настройки стиля кода, которые вы настроили в меню Tools > Options.

Чтобы получить поддержку языковых служб при редактировании EditorConfig файла в VS, загрузите расширение EditorConfig Language Service.

Вывод

Visual Studio 2017 — просто ступенька в конфигурации соглашения о написания кода. Чтобы узнать больше о поддержке EditorConfig в Visual Studio 2017, ознакомьтесь с документацией.

Подскажите сочетание клавиш для автовыравнивания кода

Добавлено через 13 минут
Форматировать фрагмент кода — жмёшь Ctrl + K, отпускаешь и сразу жмёшь Ctrl + F.
Форматировать весь код — жмёшь Ctrl + K, отпускаешь и сразу жмёшь Ctrl + D. // эта функция не всегда доступна.

Сочетание клавиш
Существует возможность создать конструктор с выделенными курсором переменными и подобными.

Случайно нажал не то сочетание клавиш — изменился вид шрифта
Хотел вставить или скопировать код (не помню) и нажал не то сочетание клавиш. И в итоге шрифт в.

сочетание клавиш для popup menu
как к action context menu приписать сочетание клавиш? этот код не работает QAction.

Сочетание клавиш для запуска макроса в Libreoffice
Всем привет, если кто знает, как назначить сочетание клавиш для запуска макроса в Libreoffice на.

Лучший ответСообщение было отмечено Bdavid008 как решение

Решение

Сочетание клавиш для макроса при открытии нескольких книг
Всем привет! Допустим у меня в файле есть макрос, к которому "привязаны" горячие клавиши ctrl+q.

Как отправить форме сочетание клавиш — Ctrl+C — для копирования выделенного текста?
Всем доброго дня. Вопрос в следующем. На форме есть некий выделенный текст, нужно его скопировать.

подскажите пожалуйста сочетание клавишь для установки виндовс
подскажите пожалуйста сочетание клавиш для установки виндовс на ноутбуке acer aspire one.

Сочетание клавиш
Подскажите как сделать так, чтобы каким нибудь сочетанием клавиш например alt+1 можно было в любом.

A Guide to Beautifying Visual Studio Code

If you like the look of your code, you’ll probably enjoy writing it more

Bret Cameron

‘Why do people pay more for a room with a good view?’ a friend asked me recently. ‘I don’t care what’s outside my window. Looking out on a natural landscape brings me no more joy than looking out on a dirty brick wall.’

The pragmatists among you might feel about the software you use to write code. Visual Studio Code is a practical tool, after all, so who cares if — visually — it is the software equivalent of a dirty brick wall?

Well, I do. In the same way that working a nice place makes me feel more production, if I enjoy the look of my code, I also enjoy writing it, editing it and painstakingly debugging it. If visuals are important to you too, then you’ve come to the right place. This article will guide you through a handful of the best themes, extensions and settings VS Code has to offer. (And if your favourite aesthetic extension is missing from this list, let me know in the comments!)

Contents

Ligatures

If you want === to look more like ≡, >= to look more like ⩾, or !== to look more like ≠, then there’s a font for you.

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

To format a selection: Ctrl + K , Ctrl + F

To format a document: Ctrl + K , Ctrl + D

See the pre-defined keyboard shortcuts. (These two are Edit.FormatSelection and Edit.FormatDocument .)

Note for macOS

On macOS, use the CMD ⌘ key instead of Ctrl :

  • To format a selection: CMD ⌘ + K , CMD ⌘ + F
  • To format a document: CMD ⌘ + K , CMD ⌘ + D

Ronan Boiteau's user avatar

For Visual Studio 2010/2013/2015/2017/2019

  • Format Document ( Ctrl+K , Ctrl+D ), i.e. press&hold Ctrl , press&release K then tap D as it is a sequence
  • Format Selection ( Ctrl+K , Ctrl+F )

Toolbar Edit -> Advanced (If you can’t see Advanced, select a code file in solution explorer and try again)

Your shortcuts might display differently to mine as I am set up for C# coding but navigating via the toolbar will get you to your ones.

If it isn’t working, look for errors in your code, like missing brackets which stop auto format from working

I have installed an extension named "Format document on Save" which formats the whole document every time you save it.

For installing it in Visual Studio 2015 or Visual Studio 2017, on Tools just click the "Extensions and Updates. ":

Enter image description here

And then just go to "Online" at the left panel and search for "Format document on save":

Enter image description here

Peter Mortensen's user avatar

Go to menu ToolsExtensions & Updates and type "productivity" in search:

1

Install ‘Productivity Power Tools 2015’

Restart Visual Studio.

Go to menu ToolsOptionsProductivity Power ToolsPower Commands and check "Format document on save":

2

Note: In VS2022 we don’t have power commands.

  • If anyone want to have "Format document on save" and "Remove and sort using on save" install Mads Kristensen extension for VS2022 https://marketplace.visualstudio.com/items?itemName=MadsKristensen.CodeCleanupOnSave
  • After installing this extension it will automatically "Format document on save", "Remove and sort using on save" and "Apply file header preferences".
  • If we want to customize default settings click on "Configure Code Cleanup" menu item to add/remove any available fixers. enter image description here

Visual Studio 2019 & 2022

  1. Format Document, While you’re holding down Ctrl button, first press K then D
  2. Format Selection, While you’re holding down Ctrl button, first press K then F

or just click Edit => Advanced => Format Document / Format Selection

enter image description here

Follow the steps below:

  • Go to menu Tools
  • Go to Options
  • Go to the Text Editor options
  • Click the language of your choice. I used C# as an example.

See the below image:

Enter image description here

Peter Mortensen's user avatar

You can define new key bindings by going to ToolsOptionsEnvironmentkeyboard:

Enter image description here

Peter Mortensen's user avatar

Sami's user avatar

Since Visual Studio 2022 17.1 there is a builtin Feature to run code formatting on save (see devblogs.microsoft), meaning there is no need to install extensions like Format document on Save .

enter image description here

Be aware that there is a failure regarding the merge view when using the autoformat option — github code cleanup — merge bug.

Kraego's user avatar

On mac : Shift + Option + F

On ubuntu : Ctrl + Shift + I

In Visual Studio 2017, 2019, 2022

Format Document is Ctrl + E , D .

But. if you want to add the Format Document button to a tool bar do this:

  • Right click on tool bar.
  • Select "Customize.."
  • Select the "Commands" Tab.
  • Select the "Toolbar" radio button.
  • Select "Text Editor" from the pull down next to the radio button (or whatever tool bar you want the button on)
  • Click the Add Command button.
  • Categories: Edit
  • Commands: Document Format
  • Click OK

Chris Catignani's user avatar

I used to use these combinations. I automated this process on Save of a document. You can try my extension Format Document on Save.

Peter Mortensen's user avatar

If you display the HTML Source Editing toolbar, there is a "Format the Whole Document" button as well.

Peter Mortensen's user avatar

The solution provided in accepted answer does not apply to Microsoft Visual Studio 2012.

In case of Visual Studio 2012, the shortcuts are:

  • For a highlighted block of code: Ctrl + K , Ctrl + F
  • For the document-wide formatting: Ctrl + K , Ctrl + D

Peter Mortensen's user avatar

Geowil's user avatar

In Visual Studio 2019 , "Code Cleanup" (RunDefaultCodeCleanup) is more advanced (taken from ReSharper): Ctrl + K , Ctrl + E

Auto formatting settings in Visual Studio

Peter Mortensen's user avatar

Paul Sumpner's user avatar

Select the text you want to automatically indent.

Click menu EditAdvanced → *Format Selection, or press Ctrl + K , Ctrl + F . Format Selection applies the smart indenting rules for the language in which you are programming to the selected text.

Peter Mortensen's user avatar

Under menu ToolsOptionsText Editor, then going to the FormattingGeneral section of whatever language you wish to format you will find General. Check all three formatting check-boxes.

Under menuToolsOptionsText Editor, then going to the TABS section of whatever language you wish to format you will find Indenting. Select Smart and it will activate automatic formatting whenever you use one of the closing elements ; ) > within that block.

There isn’t any need for keystrokes.

Peter Mortensen's user avatar

In newer versions, the shortcut for the document-wide formatting is: Shift + Alt + F

Lucas Bernalte's user avatar

You can add the buttons to your toolbar by clicking the little drop down arrow to the right of the last toolbar button, select «Add or Remove Buttons» and then click the buttons you want to add a tick to them. The button(s) you select will appear on your toolbar .

enter image description here

Then you just select text and click the Increase Indent or Decrease Indent buttons. I tested this on Visual Studio 2013 only.

Enter image description here

It works in Visual Studio 2015, maybe earlier version.

Peter Mortensen's user avatar

RayLoveless's user avatar

The original question said "I cannot find the setting."

Simple answer is: Look at top menu, then

You will also see the currently assigned key strokes for that function. Nothing special to memorize. This really helps if you use multiple developer environments on different operating systems.

Select the data and the right click and you will find this option. Format Document and Format Selection:

See this image

Peter Mortensen's user avatar

Ajit Mourya's user avatar

  1. Windows Shift + Alt + F
  2. MacOS Shift + Option + F
  3. Linux Ctrl + Shift + I

Suraj Rao's user avatar

Alok Kumar Sahoo's user avatar

Just to further Starwfanatic and Ewan’s answers, you can customise your IDE to add any button to any toolbar — so you can add the Format button (as the HTML Source Editing toolbar has) to any other toolbar (like Text Editing with all the other edit controls like increase/decrease indent).

Click the arrow to the right of the toolbar → Add or Remove ButtonsCustomize. → Commands tab → button.

Document Format and Selection Format are both under the Edit group.

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

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