Расширение для выравнивания кода visual studio code
Согласованное форматирование кода — сложная задача, но современные инструменты разработчиков позволяют автоматически обеспечивать согласованность базы кода вашей команды.
В этой статье мы настроим Prettier для автоматического форматирования кода в Visual Studio Code или VS Code.
Для демонстрации мы будем форматировать следующий код:
Если вы знакомы с форматированием кода, вы можете заметить некоторые упущения:
- Смесь одинарных и двойных кавычек.
- Первое свойство объекта person должно находиться в отдельной строке.
- Выражение консоли внутри функции должно быть выделено отступами.
- Вам могут понравиться или не понравиться необязательные скобки, в которые заключен параметр функции arrow.
Предварительные требования
Для прохождения этого учебного модуля вам нужно будет загрузить и установить Visual Studio Code.
Чтобы работать с Prettier в Visual Studio Code, вам потребуется установить расширение. Для этого выполните поиск инструмента Prettier - Code Formatter в панели расширений VS Code. Если вы устанавливаете его в первый раз, вы увидите кнопку install вместо кнопки uninstall, как показано здесь:
Шаг 1 — Использование команды форматирования документа
После установки расширения Prettier вы можете использовать его для форматирования вашего кода. Для начала выполним обзор, используя команду Format Document. Эта команда сделает ваш код более согласованным с отформатированными пробелами, переносами строк и кавычками.
Чтобы открыть палитру команд, вы можете использовать COMMAND + SHIFT + P в macOS или CTRL + SHIFT + P в Windows.
Выполните в палитре команд поиск по ключевому слову format и выберите Format Document.
Затем выберите Prettier - Code Formatter.
Примечание. Если вы не видите диалога выбора формата по умолчанию, вы можете вручную изменить его в разделе «Настройки». Установите для Editor: Default Formatter значение esbenp.prettier-vscode .
Теперь ваш код отформатирован с пробелами, переносами строк и единообразными кавычками:
Это работает и для файлов CSS. Вы можете превращать код с несогласованными отступами, скобками, разрывами строк и точками с запятой в хорошо отформатированный код. Например:
Будет переформатирован как:
Мы изучили эту команду, и теперь посмотрим, как можно реализовать ее автоматическое выполнение.
Шаг 2 — Форматирование кода при сохранении
До сих пор вам нужно было вручную запускать команды для форматирования кода. Чтобы автоматизировать этот процесс, вы можете выбрать в VS Code настройку, чтобы ваши файлы автоматически форматировались при сохранении. Это также гарантирует, что неформатированный код не попадет в систему контроля версий.
Чтобы изменить эту настройку, нажмите COMMAND + в macOS или CTRL + в Windows, чтобы открыть меню Settings (Настройки). Выполните в меню поиск Editor: Format On Save и убедитесь, что эта опция включена:
Теперь вы можете писать код как обычно, и он будет автоматически форматироваться при сохранении файла.
Шаг 3 — Изменение параметров конфигурации Prettier
Prettier выполняет много действий по умолчанию, но вы также можете внести индивидуальные изменения в его настройки.
Откройте меню Settings (Настройки). Выполните поиск Prettier. Вы увидите список всех параметров, которые вы можете изменить:
Вот несколько наиболее распространенных параметров:
- Single Quote — выберите, нужно ли использовать одинарные или двойные кавычки.
- Semi — выберите, нужно ли добавлять точку с запятой в конце строк.
- Tab Width — укажите, сколько пробелов должно вставляться при табуляции.
Недостаток использования меню встроенных параметров VS Code заключается в том, что при этом не обеспечивается согласованность между разработчиками в вашей команде.
Шаг 4 — Создание файла конфигурации Prettier
Если вы измените настройки VS Code, у другого разработчика может оказаться совершенно иная конфигурация. Вы можете обеспечить единство форматирования в своей команде, создав файл конфигурации для вашего проекта.
Создайте новый файл .prettierrc. extension с одним из следующих расширений:
Вот пример простого файла конфигурации в формате JSON:
Более конкретную информацию о файлах конфигурации можно найти в документации по Prettier. После создания такого файла и его добавления в проект вы можете быть уверены, что все члены команды используют одинаковые правила форматирования.
Заключение
Иметь согласованный код — очень хорошая практика. Это особенно полезно при работе над проектом с несколькими участниками. Согласование конфигурации делает код более удобочитаемым и понятным. Это позволяет уделить больше времени решению технических проблем, а не тратить время на исправление отступов.
Prettier обеспечивает согласованность форматирования кода и позволяет автоматизировать этот процесс.
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.
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
List members
When you type a member access symbol ( . or -> ) the editor will display a list of members. As you type additional letters, the list is filtered in real time:
Code formatting
The C/C++ extension for Visual Studio Code supports source code formatting using clang-format which is included with the extension.
You can format an entire file with Format Document ( ⇧⌥F (Windows Shift+Alt+F , Linux Ctrl+Shift+I ) ) or just the current selection with Format Selection ( ⌘K ⌘F (Windows, Linux Ctrl+K Ctrl+F ) ) in right-click context menu. You can also configure auto-formatting with the following settings:
- editor.formatOnSave - to format when you save your file.
- editor.formatOnType - to format as you type (triggered on the ; character).
By default, the clang-format style is set to "file" which means it looks for a .clang-format file inside your workspace. If the .clang-format file is found, formatting is applied according to the settings specified in the file. If no .clang-format file is found in your workspace, formatting is applied based on a default style specified in the C_Cpp.clang_format_fallbackStyle setting instead. Currently, the default formatting style is "Visual Studio" which is an approximation of the default code formatter in Visual Studio.
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.
To peek at a symbol's definition, place your cursor on the symbol anywhere it's used in your source code and then press ⌥F12 (Windows Alt+F12 , Linux Ctrl+Shift+F10 ) . Alternatively, you can choose Peek Definition from the context menu (right-click, then choose Peek Definition).
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.
To search for a symbol in the current file, press ⇧⌘O (Windows, Linux Ctrl+Shift+O ) , then enter the name of the symbol you're looking for. A list of potential matches will appear; it is filtered as you type. Choose from the list of matches to navigate to its location.
To search for a symbol in the current workspace, press ⌘T (Windows, Linux Ctrl+T ) , then enter the name of the symbol. A list of potential matches will appear as before. If you choose a match that was found in a file that's not already open, the file will be opened before navigating to the match's location.
Go to Definition
You can also quickly navigate to where a symbol is defined by using the Go to Definition feature.
To go to a symbol's definition, place your cursor on the symbol anywhere it is used in your source code and then press F12 . Or, choose Go to Definition from the context menu (right-click, then choose Go to Definition). When there's only one definition of the symbol, you'll navigate directly to its location, otherwise the competing definitions are displayed in a peek window as described in the previous section and you have to choose the definition that you want to go to.
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.
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
What is the equivalent of Ctrl + K + F and Ctrl + K + D on Windows in Visual Studio for formatting, or "beautifying" code in the Visual Studio Code editor?
For all those desperately trying to format XML (which seems not possible out of the box currently) you can achieve this by installing an extension. I have found XML Tools to get the job done just fine. Disclaimer: I am not the author nor related to this project.
While VSCode has much fewer menu options than VS (new trend?), it has extensive info and tutorials under the HELP menu, which may have answered this question.
For all those struggling to get the formatting work even after trying the valid combinations in Visual Studio Code, don't forget to select the appropriate programming language type, it is at the bottom right in visual studio code window next to that smiley. Once you do that I found it works out of the box and you don't need any additional plugin to format code.
29 Answers 29
The code formatting is available in Visual Studio Code through the following shortcuts:
- On Windows Shift + Alt + F
- On Mac Shift + Option + F
- On Linux Ctrl + Shift + I
Alternatively, you can find the shortcut, as well as other shortcuts, through the 'Command Palette' provided in the editor with Ctrl + Shift + P (or Command + Shift + P on Mac), and then searching for format document.
Open command palette (Win: F1 or Ctrl + Shift + P )
Find "Change Language Mode"
Select language e.g. json . By now syntax should be highlighted.
Format document (e.g. Open Command Palette -> "Format Document")
- Select text
- Command Palette -> Join Lines
Also note that the code Language has to be correct. ie Format Code won't be available if plain text is selected but switching to JSON (for example) will format the selected text happily. (as happy as a text editor can be anyway)
@JoSmo: On Ubuntu, I opened File > Preferences > Keyboard Shortcuts. There is an item for < "key": "ctrl+shift+i", "command": "editor.action.format", "when": "editorTextFocus" >. The command "ctrl+shift+i" works for me.
Also, apparently the file has to be saved to disk first. I had a chunk of HTML+Javascript where it couldn't format the JS, so I pasted it to a temporary window and set the language, but this didn't help either until it was saved.
This doesn't work for me on VS Code latest version and win 10 does this assume having a certain extension installed?
Code Formatting Shortcut:
Visual Studio Code on Windows - Shift + Alt + F
Visual Studio Code on MacOS - Shift + Option + F
Visual Studio Code on Ubuntu - Ctrl + Shift + I
You can also customize this shortcut using a preference setting if needed.
Code Formatting While Saving the File:
Visual Studio Code allows the user to customize the default settings.
If you want to auto format your content while saving, add the below code snippet in the work space settings of Visual Studio Code.
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:
- A mix of single and double-quotes.
- The first property of the person object should be on its own line.
- The console statement inside of the function should be indented.
- You may or may not like the optional parenthesis surrounding the parameter of the arrow function.
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:
Then choose Prettier - Code Formatter.
Note: If you do not see a prompt for selecting a default format, you can manually change this in your Settings. Set Editor: Default Formatter to esbenp.prettier-vscode .
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.
To change this setting, press COMMAND + , on macOS or CTRL + , on Windows to open the Settings menu. Once the menu is open, search for Editor: Format On Save and make sure that option is checked:
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:
- Single Quote - Choose between single and double-quotes.
- Semi - Choose whether or not to include semicolons at the end of lines.
- Tab Width - Specify how many spaces you want a tab to insert.
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.
Create a new file called .prettierrc. extension with one of the following extensions:
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.
Давайте поговорим о Code — Visual Studio Code.
Наш VSC будет пятирогим лазеростреляющим единорогом —после того как мы снабдим его самыми полезными расширения, которыми я пользуюсь каждый день.
О, а если вы еще не используете замечательный редактор VSC, под картинкой выше есть ссылка на официальный сайт, с которого его можно загрузить.
Самая эпичная тема для Visual Studio Code:
Автоматически находит, парсит и дополняет названия методов и событий для всех доступных файлов. Поддерживает Typescript и TSX.
Это расширение отобразит в редакторе размер импортируемого пакета в одной строчке с соответствующим методом. Расширение использует Webpack с babili-webpack-plugin для обнаружения импортируемого объекта и оценки его размера.
Простое расширение, которое делает отступы более читабельными.
Расширение VSCode, которое автоматически дополняет название CSS-класса для HTML-атрибута class на основе определений, найденных в вашей рабочей области или внешних файлов, на которые ссылается элемент link .
Простой способ предпросмотра SVG.
Не могу жить без него — пакет VSCode для форматирования JavaScript / TypeScript / CSS с использованием Prettier.
Подсказки, отладка и встроенные команды для React Native.
Это расширение позволяет в VSCode использовать горячие клавиши Sublime Text 3. Попробуйте потестировать его, открыв консоль сочетанием клавиш:
cmd ⌘ + P — Mac
ctrl + P — Windows
В этой консоли можно быстро перейти к файлам, а также, если добавить символ > перед поисковой строкой, можно искать действия, такие как переключение встроенного терминал, установку расширения и так далее.
Очень удобная штука для тех из нас, кто привык к ST3. 🎉
Плагин VSCode, который автоматически дополняет имена модулей npm в операциях импорта.
Добавляет подсветку синтаксиса и поддержку разметки HTML внутри строк JavaScript и TypeScript, как это используется в lit-html и других фреймворках.
Это расширение предназначено для подсветки парных открывающих или закрывающих тегов — функциональности, отсутствующей в VSCode, но которая должна бы быть встроена в редактор из коробки.
Это расширение перезагружает встроенные возможности Visual Studio Code по работе с Git. Оно в наглядном виде предоставляет информацию об авторстве изменений в Git, а также облегчает перемещение по репозиториям и позволяет отслеживать историю изменений файлов или веток, использовать команды сравнения кода и многое другое.
Git Project Manager (GPM) — это расширение Microsoft VSCode, которое позволяет вам открыть новое окно на основе git-репозитория непосредственно из VSCode.
Просмотр логов git и истории изменения файлов и сравнение веток или коммитов.
Удобный способ создания, дублирования, перемещения, переименования и удаления файлов и каталогов.
Настраиваемое расширение для раскрашивания парных скобок. Крайне полезно при работе с большим количеством обратных вызовов.
Это расширение подсвечивает CSS / веб-цвета, найденные в вашем документе.
Переход к CSS-свойствам идентификаторов (id) и классов непосредственно из файлов HTML. Поддерживает переключение и между файлами и быстрый переход из одного в другой.
Инструмент для отладки JavaScript-кода или любого другого кода в браузере Chrome.
Выполняет JavaScript-код в консоли параллельно с тем, как вы его пишете. (Полезно для быстрых демонстраций).
Мгновенно выделяет и удаляет конечные пробелы.
Это расширение пригодится всем, кто пишет на TypeScript и хочет, чтобы VSC организовал импорты за него.
Метрики, инсайты и отслеживание времени, автоматически генерируемые на основании статистики вашей работы по программированию.
Поддержка Vue для VSCode
Запустите фрагмент кода или целый файл сразу в нескольких языках.
Расширенная поддержка автозаполнения и рефакторинга кода на PHP.
Иконки для редактора VSCode.
Пользуйтесь Jest от Facebook с удовольствием.
Сниппеты кода для разработки на React.js в синтаксисе ES6.
Благодарю вас за то, что прочитали эту статью! Переходите по ссылке в твиттере, чтобы узнать о других расширениях VSCode. Знаете еще какие-то полезные плагины, которые не упомянуты здесь? Пожалуйста, пишите их в комментариях❤
Если статья оказалась полезной для вас, не забудьте поаплодировать оригиналу и переводу. Вы также можете подписаться на твиттер автора , где он часто публикует другие полезные подборки.
Читайте также: