форматирование кода в webstorm
Reformat and rearrange code
You can reformat a part of code, the whole file, group of files, a directory, and a module. You can also exclude part of code or some files from the reformatting.
If you are using specific linters or formatters, refer to corresponding pages, for example, Prettier or ESLint.
Reformat a code fragment in a file
In the editor, select a code fragment you want to reformat.
If you don’t select a code fragment, WebStorm will reformat the whole file.
Reformat a file
Keep pressing Shift and select additional files for a group reformatting.
In the dialog that opens, if you need, select the following reformatting options:
Optimize imports : select this option if you want to remove unused imports, add missing ones, or organize import statements.
For more information, refer to the Optimize imports section.
Rearrange entries : select this option if you need to rearrange your code based on the arrangement rules specified in the code style settings.
Code cleanup : select this option to run the code cleanup inspections.
If you want to see the exact changes made to your code during the reformatting, use the Local History feature.
Reformat code in a folder
Reformat line indents
You can reformat line indents based on the specified settings.
In some cases, the option Detect and use existing file indents for editing located in the Indent Detection section in File | Settings/Preferences | Editor | Code Style can override your settings. In this case WebStorm will display a notification.
Automatically reformat code on save
You can configure the IDE to reformat code in modified files automatically when your changes are saved.
Enable the Reformat code option.
Additionally, you can click Configure scope to specify the patterns of filenames and directories that you want to exclude from reformatting.
Exclude files from reformatting
You can exclude a group of files and directories from reformatting, code arrangement, and import optimization.
Switch to the Formatter tab and in the Do not format field, enter the files and directories that you want to exclude using a glob pattern.
Apply the changes and close the dialog.
Exclude code fragments from reformatting in the editor
Switch to the Formatter tab and enable the Turn formatter on/off with markers in code comments option.
The code between the markers won’t be reformatted.
The example below shows two code fragments. One of the is enclosed in the @formatter:off and @formatter:on markers while the other one is not.
The original formatting of the code inside the markers is preserved while the code without markers is reformatted:
The original formatting is not preserved in both code fragments:
Keep existing formatting
You can select formatting rules which will be ignored when you reformat the code. For example, you can adjust the IDE to keep simple methods and functions in one line, whereas normally they are expanded into multiple lines after code reformatting.
In the Keep when reformatting section, select the formatting rules which you want to ignore and deselect those which should be applied.
WebStorm will reformat your code in accordance with the current style settings, keeping existing formatting for the rules which you’ve selected.
Rearrange code
You can rearrange your code according to the arrangement rules set in the Code Style page of the Settings/Preferences dialog.
You can exclude specific files and folders from arrangement. For more information, refer to Exclude files from reformatting.
Rearrange code entries
Select a language for which you want to create arrangement rules.
On the Arrangement tab, specify the appropriate options such as grouping and matching rules.
Click OK to save the changes.
Automatically rearrange code on save
You can configure the IDE to rearrange code elements in modified files automatically when your changes are saved.
Enable the Rearrange code option.
Additionally, you can click Configure arrangement rules to specify the rules for reordering code elements for the selected language.
Configuring code style
If certain coding guidelines exist in a company, one has to follow these guidelines when creating source code. WebStorm helps you maintain the required code style.
Code styles are defined at the project level and at the IDE level (global).
At the project level, settings are grouped under the Project scheme, which is predefined and is marked in bold. The Project style scheme is applied to the current project only.
You can copy the Project scheme to the IDE level, using the Copy to IDE command.
At the IDE level, settings are grouped under the predefined Default scheme (marked in bold), and any other scheme created by the user by the Duplicate command (marked as plain text). Global settings are used when the user doesn’t want to keep code style settings with the project and share them.
You can copy the IDE scheme to the current project, using the Copy to Project command.
Configure code style for a language
Select the language-specific settings page.
Choose the code style Scheme to be used as a base for your custom code style for the selected language.
Browse through the tabs of the selected language page, and configure code style preferences for it.
Copy code style settings from other languages
For most of the supported languages, you can copy code style settings from other languages or frameworks.
Select the language-specific settings page.
Click Set From in the upper-right corner.
The link is shown for those languages only, where defining settings on the base of other languages is applicable.
From the list that appears, select the language to copy the code style from.
Manage code style on a directory level with EditorConfig
Generic IntelliJ options that have the ij_ prefix and are applicable to all languages:
In the Project view, right-click a source directory containing the files whose code style you want to define and choose New | EditorConfig from the context menu.
Select the properties that you want to define so that WebStorm creates stubs for them, or leave all checkboxes empty to add the required properties manually.
Reformat and rearrange code
You can reformat a part of code, the whole file, group of files, or a directory. You can also exclude part of code or some files from the reformatting.
Reformat a code fragment in a file
In the editor, select a code fragment you want to reformat.
If you don’t select a code fragment, PhpStorm will reformat the whole file.
Reformat a file
Keep pressing Shift and select additional files for a group reformatting.
In the dialog that opens, if you need, select the following reformatting options:
Optimize imports : select this option if you want to remove unused imports, add missing ones, or organize import statements.
For more information, refer to the Optimize imports section.
Rearrange entries : select this option if you need to rearrange your code based on the arrangement rules specified in the code style settings.
Code cleanup : select this option to run the code cleanup inspections.
Reformat code in a folder
Reformat line indents
You can reformat line indents based on the specified settings.
In some cases, the option Detect and use existing file indents for editing located in the Indent Detection section in Settings/Preferences | Editor | Code Style can override your settings. In this case PhpStorm will display a notification.
Automatically reformat code on save
You can configure the IDE to reformat code in modified files automatically when your changes are saved.
Enable the Reformat code option.
Additionally, you can click Configure scope to specify the patterns of filenames and directories that you want to exclude from reformatting.
Exclude files from reformatting
You can exclude a group of files and directories from reformatting, code arrangement, and import optimization.
Switch to the Formatter tab and in the Do not format field, enter the files and directories that you want to exclude using a glob pattern.
Apply the changes and close the dialog.
Exclude code fragments from reformatting in the editor
Switch to the Formatter tab and enable the Turn formatter on/off with markers in code comments option.
The code between the markers won’t be reformatted.
The example below shows two code fragments. One of the is enclosed in the @formatter:off and @formatter:on markers while the other one is not.
The original formatting is preserved:
The original formatting is not preserved in both code fragments:
Keep existing formatting
You can select formatting rules which will be ignored when you reformat the code. For example, you can adjust the IDE to keep simple methods and functions in one line, whereas normally they are expanded into multiple lines after code reformatting.
In the Keep when reformatting section, select the formatting rules which you want to ignore and deselect those which should be applied.
PhpStorm will reformat your code in accordance with the current style settings, keeping existing formatting for the rules which you’ve selected.
Rearrange code
You can rearrange your code according to the arrangement rules set in the Code Style. PHP page of the Settings/Preferences dialog.
Configure grouping rules
Grouping rules let you keep related class methods together.
Create matching rules
Matching rules let you define elements order as a list of rules, where every rule has a set of matching conditions, such as modifier or type.
Use the Type and Modifier filters to choose the code constructs and their visibility modifiers that should be regulated by the rule. Note that double-clicking a filter negates the condition.
Use the Name field to specify entry names the rule should affect. This filter matches only entry names, such as property names, method names, class names, and so on. The filter supports regular expressions and uses a standard syntax. The match is performed against the entire name.
You can also create groups (aliases) of rules and refer to them when creating a new matching rule.
Create rule aliases
With aliases, you can group several arrangement rules into a single entity and refer to it when you adding a new matching rule.
In the Rules Alias Definitions dialog that opens, add a group name and its rules.
The created alias can now be referred to when adding a matching rule.
Create section rules
Section rules let you move methods or variables into the sections that you have defined.
For example, you can create the following section rule:
After the arrangement, methods in the class will be rearranged as specified in the created section rule and will be surrounded by comments:
You can exclude specific files and folders from arrangement. For more information, refer to Exclude files from reformatting.
Rearrange code entries
Select a language for which you want to create arrangement rules.
On the Arrangement tab, specify the appropriate options such as grouping and matching rules.
Click OK to save the changes.
Automatically rearrange code on save
You can configure the IDE to rearrange code elements in modified files automatically when your changes are saved.
Enable the Rearrange code option.
Additionally, you can click Configure arrangement rules to specify the rules for reordering code elements for the selected language.
Шпаргалка: Горячие (hotkeys) клавиши PhpStorm и PyCharm
Горячих клавиш в IDE PhpStorm и PyCharm гораздо больше, чем в приведенном ниже списке. Здесь я привел только те, которыми пользуюсь сам (* звездочкой выделил наиболее используемые мною горячие клавиши).
Шпаргалка будет обновляться, если начну использовать новые hotkeys.
Для настройки горячих клавиш или добавление собственных сочетаний клавиш перейдите File > Settings > Keymap.
Редактирование
*Ctrl + W — выделение текущего блока. Если нажимать W несколько раз, то будут выделяться родительские блоки по иерархии.
Ctrl + Shift + W — проделывает обратное действие от предыдущего
Ctrl + Y — удаляет строку
*Ctrl + D — дублирует строку
Ctrl + Shift + U — делает выделенный текст или заглавными, или строчными буквами
Ctrl + Delete — удаляет часть от курсора до конца слова
*Ctrl + Alt + L — форматирование кода соответствии с настройками code style.
*Ctrl + / — закомментировать/раскомментировать текущую строку.
Ctrl + Shift + / — закомментировать/раскомментировать выделенные строки кода.
Ctrl + Shift + J — к текущей строке присоединяет нижнюю.
Ctrl + [ или ] — перемещает курсор в начало или конец блока с кодом, в теле фукции, в теле цикла и т.д.
Ctrl + Shift + ] или [ — выделить код код до конца или до начала блока
*Tab — сделать отступ (табуляцию)
*SHIFT + Tab — убрать отступ
*Ctrl + Alt + Стрелка вверх — перемещает текущую строку вверх.
*Ctrl + Alt + Стрелка вниз — перемещает текущую строку вниз.
Ctrl + Shift + Стрелка вниз — перемещает текущий логический блок вниз
*Ctrl + Space — выводит возможные варианты автодополнения
Ctrl + курсор мыши над кодом — краткая информация
*Ctrl + клик по названию переменной или метода, или CTRL+B когда курсор установлен на названии, приведет туда, где метод или переменная определены.
*Ctrl + G — перейти к строке по номеру
*Alt + Клик левой кнопкой мышки — мультикурсор, если нужно одновременно несколько курсоров, кликаем мышкой в нужные места, куда нужно их добавить
*Ctrl + Alt + J — обрамление выделенного текста тегом (нужно выбрать первый пункт из всплывающего окошка)
F11 — быстро установить закладку
Shift + F11 — просмотр всех закладок
Поиск / замена
Двойной Shift — поиск по проекту
*Ctrl + F — поиск в текущем файле
*Ctrl + R — поиск и замена
*Ctrl+Shift+E — вызовет всплывающее окно, в котором показаны последние куски кода в разных файлах, с которыми вы работали
Ctrl + Shift + F — поиск в группе файлов (например в проекте или папке)
Ctrl + Shift + R — поиск и замена в группе файлов
Ctrl + N — найти в каком файле находится класс
*Ctrl + Shift + N — поиск файла по названию
Разное
Ctrl + Alt + S — быстрый доступ к настройкам
*Shift + F6 — переименование файла (выделите в блоке с файлами проекта нужный файл).
WebStorm 2020.2: возможность использовать Prettier по умолчанию, поддержка Nuxt.js и другие улучшения
Всем привет! Мы рады представить второе крупное обновление WebStorm в этом году. В нем вы найдете несколько долгожданных улучшений, включая поддержку Nuxt.js и возможность использовать Prettier для форматирования кода по умолчанию.
Скачать 30-дневную пробную версию WebStorm 2020.2 можно на сайте или с помощью Toolbox App. Полную версию могут использовать обладатели действующей подписки на WebStorm или All Products Pack, а также бесплатно студенты и разработчики опенсорсных проектов.
А сейчас давайте рассмотрим основные улучшения.
Форматируйте код с помощью Prettier по умолчанию
Новую опцию On code reformat можно найти в Preferences/Settings | Languages & Frameworks | JavaScript | Prettier.
Существующие до этого способы использования Prettier также никуда не делись. Допустим, вы привыкли к действию Reformat with Prettier и даже добавили кастомную комбинацию клавиш для него. Все это будет работать и в версии 2020.2.
Поддержка Nuxt.js и другие улучшения для Vue
Весь последний год мы активно работали над тем, чтобы максимально улучшить поддержку Vue в WebStorm, и в этом релизе добавили несколько финальных штрихов. Надеемся, теперь работать с проектами Vue в WebStorm станет еще удобнее.
Помимо уже существующей функциональности версия 2020.2 включает в себя поддержку Nuxt.js. В нее входит несколько вещей. Из основного – автодополнение кода для всех ключевых компонентов Nuxt, поддержка специфичной для Nuxt конфигурации webpack, а также правильное определение ссылок на Vuex store и изображений в директории static. Подробнее про поддержку Nuxt вы можете прочитать тут.
В WebStorm 2020.2 вы также найдете отдельную секцию для настроек стиля кода Vue. В ней можно быстро выбрать, какой отступ должен быть у верхнеуровневых тегов. Вы также можете решить, должен ли отступ быть одинаковым для всего файла Vue или зависеть от языковых настроек, и то, каким должно быть форматирование для интерполяций.
Помимо двух крупных улучшений, мы добавили еще несколько, подробнее о них здесь.
Новые intention-действия и другие улучшения для JavaScript
Новые intention-действия помогут вам быстрее выполнять некоторые задачи вокруг циклов, а также optional chaining и nullish coalescing. Например, WebStorm может помочь вам преобразовать цикл for в forEach. Чтобы посмотреть доступные в текущем контексте intention-действия, нажмите Alt+Enter, затем выберите подходящее действие и нажмите Enter.
Еще одно улучшение коснулось комментариев JSDoc. WebStorm научился отображать их более аккуратно, сводя к минимуму все отвлекающие факторы. Чтобы попробовать, как это работает, нажмите на новую иконку справа от комментария. Если комментарии отображаются недостаточно крупно, или, наоборот, вам хочется уменьшить их, попробуйте нажать правой кнопкой мыши на них и отредактировать размер шрифта под Adjust Font Size.
Наконец, в прошлом году мы начали экспериментировать с использованием алгоритмов машинного обучения для улучшения качества автодополнения кода. Работа еще не закончена, но вы уже можете оценить первые результаты.
Чтобы сделать это, отметьте галочку Rank completion suggestions based on Machine Learning, которая находится в Preferences/Settings | Editor | General | Code Completion, и выберите язык(и), для которых вы хотели бы попробовать новую функциональность.
Важно отметить, что ваши личные данные и код никуда не отправляются. Если вы пользуетесь EAP-билдами, мы собираем только анонимные данные об использовании автодополнения кода. Для стабильных релизов наподобие 2020.2 мы не собираем даже это.
Улучшенная поддержка модульной системы Sass
Новые инструменты для нахождения ошибок в коде
Чтобы облегчить процесс поиска ошибок в коде, мы добавили виджет Inspections и окно Problems.
Новый виджет находится в верхнем правом углу редактора. С его помощью вы можете узнать, сколько проблем в текущем файле, а также быстро переместиться от одной проблемы к другой, пользуясь стрелками или F2. Еще вы можете настроить уровень подсветки ошибок прямо из виджета: наведите на него курсор и выберите None, Syntax или All Problems.
При клике на виджет открывается новое окно Problems, которое помогает посмотреть на проблемы в текущем файле в целом. Из окна вы можете быстро перейти к любой проблеме, а также посмотреть доступные исправления и применить их. В дальнейшем мы планируем расширить список доступных действий, добавив более тесную интеграцию с TypeScript language service и возможность просматривать ошибки во всем проекте.
Расширенная поддержка GitHub пул реквестов
В WebStorm 2020.2 мы расширили поддержку пул-реквестов в GitHub и сделали работу с ними более удобной. Теперь можно просматривать и объединять все пул-реквесты, а также проверять код прямо из IDE.
Подробнее о том, что было добавлено, мы рассказали в этом блог-посте.
На этом всё на этот раз. Спасибо, что дочитали до конца! Вопросы, пожелания и просто мысли высказывайте в комментариях. Мы, как и всегда, будем рады ответить. Баг-репорты можно создать тут.
Команда JetBrains WebStorm
The Drive to Develop