выравнивание кода в 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.
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.
Горячие клавиши в PhpStorm.
Далее в горячих клавишах используют Up и Down — подразумевается использование клавиатурных стрелок Вверх, Вниз.
Ctrl + Space — предлагает вариант дополнения кода. (Вы набираете код, и если вариант имеется единственный, то происходит автодополнение).
Ctrl + Space — покажет все доступные методы для объекта (набираете $this->logger-> и здесь комбинацию, — увидите все методы для объекта в переменной).
Ctrl + D — скопировать текущую строку.
Ctrl + Y — удалить текущую строку.
Ctrl + Alt + Up — перемещает текущую строку вверх.
Ctrl + Alt + Down — перемещает текущую строку вниз.
Ctrl + Q — всплывающее окно с документацией по функции.
Ctrl + P — всплывающее окно с подсказкой о параметрах и их типах, которые ожидает функция или метод. (используйте, когда курсор в () ).
Поиск.
Ctrl + F — поиск по текущему файлу.
Ctrl + Shift + F — поиск по проекту, конкретной директории и др.
два раза Shift — поиск по всему проекту.
Ctrl + Alt + S — быстрый доступ ко всем настройкам PhpStorm
Ctrl + Shift + J — к текущей строке присоединяет нижнюю.
Ctrl + F4 — закрытие текущей вкладки редактора.
Shift + F6 — переименование файла (выделите в блоке с файлами проекта нужный файл).
Ctrl + [ — перемещает курсор в начало блока с кодом. (например в теле фукции, в теле цикла и т.д.)
Ctrl + ] — перемещает курсор в конец блока с кодом. (например в теле фукции, в теле цикла и т.д.)
Shift + F2 — перемещает курсор к блокам кода, подсвеченных как ошибки.
Ctrl + Alt + B — для метода интерфейса покажет какие классы его реализовывают.
Ctrl + Shift + T — меню создание файла теста на класс.
Ctrl + Z — отмена последнего действия.
Ctrl + Shift + Z — вернуть изменения, которая были отменены командой Ctrl + z.
Ctrl + Shift + V — вставка из буфера с возможностью выбора последних скопированных из истории.
Ctrl + Alt + I — выравнивание отступов в коде.
Ctrl + Alt + L — приведение кода в соответсвие с code style.
Ctrl + / — закомментировать/раскомментировать текущую строку.
Ctrl + Shift + / — закомментировать/раскомментировать выделенные строки кода.
Shift + Esc — сворачивает дополнительные окна (такие как терминала, контроля версий, подключения к БД и т.д.).
Секреты быстрого кодинга в WebStorm
Сегодня — немного практических советов по работе с WebStorm.
Вначале пишем совсем простой HTML, после color: нажимаем и получаем список цветов.
КО подсказывает: во всех IDE от JetBrains — это контекстная подсказка.
Как только мы выбрали цвет, на вертикальной полоске слева от текста тут же появляется маленький квадрат такого же цвета. Теперь можно кликнуть по нему, и откроется палитра, из которой можно выбрать вообще любой цвет.
А теперь представим себе проект посложнее, небольшое приложение под node.js.
Говорят, что IDE от JetBrains хороши вниманием к деталям и пониманием контекста. Вот, казалось бы, мелочь: мне надо для тестирования этого приложения сделать простенькую страницу с формой на HTML. Сделал, попробовал, усложнил приложение, тест тоже надо усложнять: переделываю форму так, чтобы она выглядела удобно для заполнения нескольких полей.
Начинаю вводить в конце строки тэг Нажимаю клавишу , срабатывает автодополнение, получаю function, дальше можно продолжать: имя и тело функции. В WebStorm есть два способа автодополнения: — это дополнить с вставкой текста, а — с заменой текста справа от курсора до разделителя (убирает неверно написанные ключевые слова и имена).
Когда ставишь открывающую фигурную скобку, тут же ставится закрывающая — и захочешь, а не забудешь ее в конце тела функции. Нажимаешь Enter — и она любезно отъезжает не на следующую строку, а на две строки вниз, открывая место для тела функции.
Надо размножить строку, скажем, однотипное поле формы? (от слова Duplicate).
Еще немного хитростей для тех, кто, как я, недавно пишет под node.js:
1) Если в node.js при запуске приложения из WebStorm возникает ошибка
это, скорее всего, значит, что вы пытаетесь запустить еще одну копию сервера node.js (а на одном TCP-порте может жить только одна копия). Чтобы этого избежать, надо в Run | Edit Configurations в ветке node.js для вашего приложения (например, index.js) поставить галочку check no other instances are running.
2) Если в приложении есть require(‘модуль’), а определения (например, функций) из этого модуля в IDE не видны, и по Ctrl-B недоступны, похоже, вы цинично нарушаете рекомендации разработчиков node.js: если вы используете модуль в проекте, надо его устанавливать локально.
Это значит (спасибо Сергею Симончику за разъяснение!), что в папке проекта должна быть папка node_modules, и в ней должны быть папки соответствующих модулей. Если папки нет, и по команде npm install модуль она не создается, ее надо создать руками, а в корневой папке проекта в командной строке дать команду npm install модуль.
Программа npm туповата (или чересчур умна): если у вас в корне проекта нет node_modules, а выше корня проекта есть папка node_modules, локальная установка модуля произойдет в нее.
Если же модули установлены правильно, а WebStorm продолжает подчеркивать функции из модулей серой волнистой линией («не определены»), то надо отметить, какие библиотеки node.js вы подключаете:
3) Проверку кода «на лету» в WebStorm можно делать аж тремя разными способами, все три — весьма гибкие: JSLint, JSHint и внутренний инспектор кода. По умолчанию включен только внутренний инспектор, который можно нечеловечески гибко настраивать в меню Settings->Inspections.
Если же надо включить JSHint или JSLint, то это делается в меню Javascript | Code Quality Tools. Оба этих инструмента — внешние, но они идут в комплекте с WebStorm и прозрачно интегрированы в IDE.
При включении любых способов проверки кода в окне редактора тут же подчеркивается то, что кажется инспекторам ошибками, а на полосе индикации ошибок справа от текста возникает множество красных и желтых черточек, вопиющих о необходимости исправить код вручную. В зависимости от того, пишете ли вы код для выполнения в браузере или на сервере, вы можете включать разные настройки инспекторов, так как некоторый вполне корректный код для node.js JSLint по умолчанию жестко критикует.
Не всем постоянно нужна проверка правописания встроенным инспектора кода. Я не хочу называть переменные в своем коде словами английского языка, а всякие там qry_1 и qry_2 подчеркиваются зеленой волнистой линией (не говоря уже о названиях полей в БД, которые тоже в коде попадаются). Отключить проверку правописания можно в Settings | Inspections | Spelling.
Конечно, это далеко не все секреты удобного кодирования в WebStorm, и если хабрасообщество одобрит текст, то в следующих выпусках мы будем говорить о поддержке TypeScript, SourceMaps и некоторых полезных горячих клавишах.
UPD: Специально для тех, кто молча ставит минус: как всегда, автор будет благодарен не только тем, кто доволен, но и тем, кто расскажет, что разочаровало, и что хотелось бы видеть. Вместе мы сделаем мир лучше.
Шпаргалка: Горячие (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 — переименование файла (выделите в блоке с файлами проекта нужный файл).