выравнивание кода в 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:

выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    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.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    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.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    The original formatting of the code inside the markers is preserved while the code without markers is reformatted:

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    The original formatting is not preserved in both code fragments:

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    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.

    Источник

    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.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    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.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    The original formatting is preserved:

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    The original formatting is not preserved in both code fragments:

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    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.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    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.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    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.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    The created alias can now be referred to when adding a matching rule.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    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:

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    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.

    Источник

    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.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    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.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Источник

    Топ-10 полезных сочетаний клавиш WebStorm

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

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

    Все приведенные здесь сочетания клавиш — стандартные для macOS и Windows / Linux. Настроить удобные для вас сочетания клавиш можно в Preferences / Settings | Keymap.

    Search Everywhere (поиск повсюду): ⇧⇧ / Shift+Shift

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

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Чтобы ограничить область поиска, перейдите на нужную вкладку или нажмите ⇥ / Tab. Кроме того, как показано на анимированном изображении ниже, прямо во всплывающем окне можно включить или отключить некоторые действия.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Show Context Actions (показать контекстные действия): ⌥↵ / Alt+Enter

    WebStorm предлагает множество intention-действий, позволяющих быстро применять исправления, генерировать код и менять настройки проекта. Если код подчеркнут волнистой линией или в редакторе WebStorm появилась лампочка, можно щелкнуть по этой лампочке или переместить курсор на подчеркнутый код и нажать ⌥↵ / Alt+Enter — IDE покажет перечень доступных контекстных действий.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    А как быть, если вы не хотите использовать какое-то действие или видеть предупреждения? Переместите курсор на код, нажмите ⌥↵ / Alt+Enter, а затем щелкните по стрелке рядом с инспекцией, которая вам не нужна, и отключите ее. Инспекция будет отключена во всем проекте.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Подробнее об инспекциях и о том, что с ними можно сделать, — на этой странице.

    Refactor This (рефакторинг кода): ⌃T / Ctrl+Alt+Shift+T

    Как и другие IDE JetBrains, WebStorm предлагает широкие возможности рефакторинга. Чтобы быстро перейти к списку доступных рефакторингов выбранного кода, нажмите ⌃T / Ctrl+Alt+Shift+T.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Go to Declaration (переход к объявлению): ⌘B or ⌘+Click / Ctrl+B or Ctrl+Click

    WebStorm позволяет мгновенно перейти к объявлению символа: просто нажмите или Ctrl и щелкните на символ. Можно также поместить на него курсор и нажать ⌘B / Ctrl+B. Кроме того, это сочетание клавиш позволяет перейти к файлу, на который есть ссылка, или импортированному модулю.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

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

    Code completion with replace (автодополнение кода с заменой): ⇥ / Tab

    Когда вы начинаете вводить код в WebStorm, автоматически появляется всплывающее окно автодополнения. Чтобы выбрать один из предложенных вариантов, можно просто нажать ↵ / Enter. Но если вы хотите заменить один вариант на другой, нажмите ⇥ / Tab, и вместо подставленного элемента появится выбранный.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Extend Selection (расширение области выделения): ⌥↑ / Ctrl+W

    Действие Extend Selection позволяет быстро расширить область выделения, не используя мышь. Чтобы снова сузить область, используйте сочетание клавиш ⌥↓ / Shift+Ctrl+W.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Run (запуск): ⌃⌥R / Alt+Shift+F10

    Самый просто способ запустить одну из конфигураций запуска проекта — нажать ⌃⌥R в macOS или Alt+Shift+F10 в Windows/Linux и выбрать нужную конфигурацию во всплывающем окне.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Подсказка: чтобы начать отладку, не запуская конфигурацию, выберите из списка конфигурацию запуска и, удерживая ⇧ / Shift, нажмите ↵ / Enter.

    Expand Live Template (развернуть шаблон Live Template): ⇥ / Tab

    Шаблоны Live Template экономят массу времени. Наберите короткое сокращение и нажмите ⇥ / Tab, чтобы развернуть его в код. Кроме того, WebStorm поддерживает аббревиатуры Emmet для HTML и CSS — их тоже можно развернуть с помощью сочетания клавиш ⇥ / Tab.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Чтобы перейти в шаблоне от одного заполнителя переменной к другому, еще раз нажмите ⇥ / Tab.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    WebStorm включает в себя большую коллекцию шаблонов Live Template, в том числе постфиксные шаблоны. Вы также можете добавить собственные пользовательские шаблоны. Подробнее о работе с шаблонами Live Template — в этой статье в блоге.

    Multiple carets (несколько курсоров): ⌥+Click / Alt+Click

    Очень популярная возможность использования нескольких курсоров есть и в WebStorm. Чтобы добавить или удалить дополнительные курсоры, нажмите и удерживайте ⌥ / Alt, а затем щелкните там, куда нужно поместить следующий курсор, чтобы эти места можно было редактировать одновременно.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Подробнее о работе с несколькими курсорами — в нашей документации.

    Scratch File (вспомогательный файл): ⇧⌘N / Ctrl+Alt+Shift+Insert

    Вспомогательные файлы (scratch files) позволяют быстро создавать образцы кода или делать заметки по ходу работы в IDE, не затрагивая рабочие файлы проекта. Вспомогательные файлы сохраняются в IDE и доступны из любого проекта.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Другие сочетания клавиш

    Интересно, что еще есть в запасе у WebStorm? О других сочетаниях клавиш можно узнать из списка горячих клавиш, доступного из главного меню IDE — Help | Keymap Reference, — или на нашем веб-сайте.

    Можно также перейти в Preferences / Settings | Keymap или просто начать набирать имя действия во всплывающем окне Search Everywhere.

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    Надеемся, что эти сочетания клавиш помогут вам сэкономить время. Какое сочетание ваше любимое? Расскажите об этом в комментариях!

    Ваша команда WebStorm
    The Drive to Develop

    Источник

    Горячие клавиши WEBStorm

    Всем привет! Сегодня я хочу вам рассказать о самых полезных горячих клавишах WEBStorm. В этой статье не будет воды, только по сути. Знание этого небольшого списка сделает вашу работу с файлами и с редактированием текста намного быстрее!

    Для удобства сочетание клавиш будет написано так же под macOS. Первыми рассмотрим горячие клавиши для работы с файлами.

    CTRL + F / ⌘ + F этим сочетанием клавиш можно осуществить поиск по открытому файлу, а использовав за этим сочетание клавиш CTRL + R / ⌘ + R можно заменить все найденные вхождения на введённое

    CTRL + SHIFT + F / ⌘ ⇧ + F осуществляет поиск по всему проекту, в котором так же как и в предыдущем пункте можно использовать сочетание ⌘ ⇧ + R / CTRL + SHIFT + R для замены

    ALT + / ⇧ ⌘ ] / ⇧ ⌘ [ передвижение между открытыми вкладками

    SHIFT + F6 / ⇧ F6 быстрое переименование файла

    CTRL + ALT + SHIFT + T / ⌃ T быстрое открытие рефакторинга (переименования и тд)

    DOUBLE SHIFT поиск по всем названиям файлов и функций

    CTRL + F4 / ⌘ W закрыть активную вкладку

    CTRL + E + ⌘ E открыть список недавно открываемых вкладок

    Следующей категорией горячих клавиш рассмотрим сочетания для удобного редактирования текста.

    Зажав CTRL + SHIFT / ⌘ ⇧ и стрелки вниз вверх можно перемещать в пределах текущей вложенности выделенный кусок кода / строку на которой стоял курсор.

    CTRL + ALT + L / ⌘ ⌥ L стандартное форматирование кода в WEBStorm

    CTRL + backspace / ⌥ ⌫ удалить целое слово

    чтобы поставить мультикурсор, нужно навести на место постановки, зажать ALT / ⌥ и кликнуть

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    ALT + ENTER / ⌥ выделение лампочки, на которую мы обычно наводим чтобы получить быстрые решения проблемы в коде

    CTRL + D / ⌘ D дублирование строки или выделенного блока кода

    Если зажать колесо мышки, можно выделить повторения кода, идущее друг под другом и сразу же заменить

    выравнивание кода в webstorm. Смотреть фото выравнивание кода в webstorm. Смотреть картинку выравнивание кода в webstorm. Картинка про выравнивание кода в webstorm. Фото выравнивание кода в webstorm

    CTRL + / / ⌘ / быстрое комментирование/раскоментирование кода

    Так же в экстренный момент могут быт полезны горячие клавиши для работы с гитом

    CTRL + K / ⌘ K коммит проекта в систему контроля версий

    CTRL + SHIFT + K пуш проекта в систему контроля версий

    Ну вот и всё, что стоит знать о горячих клавишах в IDE WEBStorm. Научитесь использовать эти клавиши и все ваши коллеги или друзья программисты будут удивлены вашей скорости при показе вами экрана! 🙂

    Источник

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

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