Jetbrains найти и заменить

Обновлено: 01.07.2024

Краткая шпаргалка по сочетаниям клавиш в IntelliJ IDEA

Как ранее уже сообщалось, я начал активно изучать возможности IntelliJ IDEA. В частности, я стараюсь запомнить наиболее востребованные хоткеи, чтобы выполнять большую часть работы, не отрывая руки от клавиатуры, как это происходит при программировании в Vim. По моим наблюдениям, это реально экономит кучу времени. Я сделал для себя шпаргалку по хоткеям IDEA, которую вы найдете под катом. Полагаю, она также пригодится кому-то из посетителей данного блога.

Примечание: Те же сочетания клавиш работают и в других продуктах JetBrains, например, PyCharm и CLion.

Ниже не приводятся общеизвестные и очевидные сочетания вроде Ctr+C, Ctr+V или Ctr + S. В IntelliJ IDEA многие хоткеи имеют парный хоткей отличающийся только тем, что в нем дополнительно участвует клавиша Shift. Обычно она добавляет в том или ином виде выделение текста. Например, Ctr + End переводит курсор в конец файла, а Ctr + Shift + End выделяет код от текущей позиции до конца файла. Догадаться о существовании парных хоткеев несложно, поэтому далее они не приводятся. Наконец, если в любом диалоге IntelliJ IDEA вы видите подчернутые буквы, знайте, что сочетание Alt + буква равносильно использованию соответствующего контрола (обычно кнопок). Например, быстро запушить код в репозиторий можно путем нажатия Ctr + K, Alt + I, Alt + P, а затем снова Alt + P.

Итак, основные сочетания следующие.

Редактирование:

Ctr + Z Undo, отменить последнее действие
Ctr + Shift + Z Redo, отменить последнюю отмену действия
Ctr + Shift + V Расширенная вставка из буфера обмена (с историей)
Ctr (+ Shift) + W Инкрементальное выделение выражения
Ctr + влево/вправо Перемещение между словами
Ctr + вверх/вниз Прокрутка кода без изменения позиции курсора
Ctr + Home/End Переход в начало/конец файла
Shift + Del (Ctr + Y) Удаление строки, отличие в том, где потом окажется курсор
Ctr + Del Удалить от текущей позиции до конца слова
Ctr + Backspace Удалить от текущей позиции до начала слова
Ctr + D Дублировать текущую строку
Tab / Shift + Tab Увеличить / уменьшить текущий отступ
Ctr + Alt + I Выравнивание отступов в коде
Ctr + Alt + L Приведение кода в соответствие code style
Ctr + / Закомментировать/раскомментировать текущую строку
Ctr + Shift + / Закомментировать/раскомментировать выделенный код
Ctr + -/+ Фолдинг, свернуть/развернуть
Ctr + Shift + -/+ Фолдинг, свернуть/развернуть все
Ctr + Shift + . Сделать текущий скоуп сворачиваемым и свернуть его
Ctr + . Сделать текущий скоуп несворачиваемым
Ctr + R Замена в тексте
Ctr + Shift + R Замена во всех файлах

Окна, вкладки:

Alt + влево/вправо Перемещение между вкладками
Ctr + F4 Закрыть вкладку
Alt + циферка Открытие/закрытие окон Project, Structure, Changes и тд
Ctr + Tab Switcher, переключение между вкладками и окнами
Shift + Esc Закрыть активное окно
F12 Открыть последнее закрытое окно
Ctr + колесико Zoom, если он был вами настроен

Закладки:

Подсказки и документация:

Ctr + Q Документация к тому, на чем сейчас курсор
Ctr + Shift + I Показать реализацию метода или класса
Alt + Q Отобразить имя класса или метода, в котором мы находимся
Ctr + P Подсказка по аргументам метода
Ctr + F1 Показать описание ошибки или варнинга
Alt + Enter Показать, что нам предлагают «лампочки»

Поиск:

Генерация кода и рефакторинг:

Прочее:

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

Дополнение: В последних версиях IDEA можно использовать несколько курсоров, разместив их либо при помощи комбинации Alt+Shift+ЛКМ, либо вертикальным выделением при помощи клика средней клавишей мыши. Держа на вооружении сочетание Ctr + влево/вправо, осуществляющего переход между словами, а также другие, можно очень удобно редактировать сразу несколько строк кода.

You can quickly find and replace text strings in the current document. Using different options, you can narrow your search process, use regular expressions in your search, and manage your search results.

If you are looking for types, members, files, actions, or settings, use Search Everywhere ( Ctrl+T or Shift twice).

Search text in the current document

Press Ctrl+F or choose Edit | Find | Find from the main menu. The search pane appears at the top of the active editor.

If necessary, specify the search options.

In the search field, start typing the search string:

Find text

As you type, the first occurrence of the search string after the current cursor position is selected; the other occurrences are highlighted in the editor. In addition, the matching occurrences are marked in the scrollbar with stripes.

To search for a multi-line fragment, click in the search box or press Ctrl+Shift+Enter

To return to a single-line mode, press Backspace .

To search for symbols declared or used in the current document, start typing a symbol name or its Camel-Cased abbreviation, and then press Ctrl+Space to choose from the matched items.

JetBrains Rider: Looking for symbols from the search field (Ctrl+F)

Replace text in the current file

Press Ctrl+R or choose Edit | Find | Replace from the main menu. The search and replace pane appears on top of the active editor.

In the search field, start typing the search string. As you type, the matching occurrences are highlighted in the editor, and a Replace popup dialog opens at the first occurrence, suggesting to replace the current occurrence, or all of them, with an empty string.

Type the replacement string.

Click Replace All to replace all matching occurrences or Replace to replace items one by one.

Alternatively, you can click Exclued to skip the current occurrence and exclude it from the Replace all operation. The button for this occurrence changes to Include . Use Shift+F3 and F3 to move focus to other occurrences that you want to exclude or include.

Explore the search results

To initiate a new search, do one of the following (depending on the current focus):

If the editor has the focus, press Ctrl+F .

If the search field has the focus, press Ctrl+A

In both cases, the existing search string will be selected, and you can start typing a new one.

To jump between occurrences, do one of the following:

Press Shift+F3 (jump to previous selection) or F3 (jump to next selection).

Use the or buttons in the Search pane.

Click the gutter stripes.

Next to the search field, you will see the total number of found occurrences and the number of the selected occurrence.

You can click or press Alt+Down to show the list of recent search entries.

To close the search pane and switch the focus to the editor, press Escape .

When you press Escape and return the focus to the editor, the first search match stays selected, so you can copy Ctrl+C or cut Ctrl+X it, or start typing to replace the selection.

You can also add multiple carets and selection ranges to the occurrences of the search string — click Alt+J and Alt+Shift+J to select or unselect occurrences one by one, or click Ctrl+Alt+Shift+J to select all occurrences.

Search and replace options

Alt+Down

Show the history of the recent entries.

Clear the search field.

Enable entering the search string in several lines. Even without this option, you can search for multiline matches with regular expressions and escape characters.

Distinguish between upper and lowercase letters while searching.

Search for whole words only, that is, for character strings separated with spaces, tabs, punctuation, or special characters.

This option is unavailable if Regular expressions is selected.

Process the search query as a regular expression.

Navigate through the occurrences of the search string.

Alt+F7

Show search results in the Find window.

Add the next found occurrence to a multiple selection.

Remove the found occurrence from a multiple selection.

Create a multiple selection that contains all the found occurrences.

Confine search and replacement to the current selection in the editor.

Invoke the list of additional options, for example to confine the search to comments or string literals.

When replacing strings, use the casing of each occurrence for replacements. For example, when replacing foo with bar , Foo will be replaced with Bar , and FOO with BAR .

When you want to search and replace specific patterns of text, use regular expressions. They can help you in pattern matching, parsing, filtering of results, and so on. Once you learn the regex syntax, you can use it for almost any language.

Press Ctrl+R to open the search and replace pane.

If you need to search and replace in more than one file, press Ctrl+Shift+R . For more detailed information, refer to Search and replace a target within a project.

Enter a search string in the top field and a replace string in the bottom field.

Regex search and replace fields

Click to enable regular expressions. If you want to check the synax of regular expressions, hover over and click the Show expressions help link.

When you search for a text string that contains special regex symbols, IntelliJ IDEA automatically escapes them with backlash \ in the search field.

Keep in mind that if you copy ( Ctrl+C ) the string first and then paste ( Ctrl+V ) it in the search field, the regex symbols will not be taken into account.

Escape regex symbols

For example, if you need to find . , type \. in the search field.

IntelliJ IDEA can also match a letter case when you enter a range of characters in your search field.

For example, if you want to search for only uppercase characters, type the following in the search field:

To search and replace more complicated patterns, use the structural search and replace.

If is unselected in the search field, IntelliJ IDEA searches for both lower and upper cases.

Select in the search field to match the case of the specified range.

The result of the Match Case selection

When you browse the occurrences, IntelliJ IDEA displays the replacement hints, so you can view the potential results before clicking the Replace button.

Replacement hints

See RegEx syntax for more details.

Use regex capturing groups and backreferences

You can put the regular expressions inside brackets in order to group them. Each group has a number starting with 1, so you can refer to (backreference) them in your replace pattern. Note that the group 0 refers to the entire regular expression. However, you can refer to the captured group not only by a number $n , but also by a name $ .

For example, for the numbered capturing groups, use the following syntax:

You can search for a text string within a project, use different scopes to narrow your search process, find occurrences, and exclude certain items from the search.

Find the search string in a project

From the main menu, select Edit | Find | Find in Files Ctrl+Shift+F .

In the search field, type your search string. Alternatively, in the editor, highlight the string you want to find and press Ctrl+Shift+F . IntelliJ IDEA places the highlighted string into the search field.

To see a list of your previous searches, press Alt+Down .

If you need, specify the additional options.

Find in Files

IntelliJ IDEA lists the search strings and the files that contain them. If the search string is found several times on the same line of code, IntelliJ IDEA merges the results in one line.

To do a multi-line search, click the icon to enter a new line, and press Ctrl+Alt+Down / Ctrl+Alt+Up to browse through occurrences.

Check the results in the preview area of the dialog where you can replace the search string or select another string, press Ctrl+Shift+F again and start a new search.

To see the list of occurrences in a separate tool window, click Open in Find Window . Use this window and its options to group the results, preview them, and work with them further.

If you want to see each new search result in a separate tab in the Find tool window, click on the bottom of the Find in Files dialog and select the Open Results in New Tab checkbox.

Narrow your search

You can use different options in the Find in Files dialog to adjust your search process.

Select options such as Words () or Match case () to find the exact word in a project or match the letter case.

With selected, IntelliJ IDEA automatically escapes special regex symbols with backslash \ when you search for a text string that contains them.

Keep in mind that if you copy ( Ctrl+C ) the string first and then paste ( Ctrl+V ) it in the search field, the regex symbols will not be taken into account.

Escape regex symbols

For more details on regex , refer to the search with regex documentation.

Click the icon to filter your search. For example, you can filter the search to omit comments or search only in comments instead.

Select one of the displayed options such as Module or Directory to limit your search.

Moreover, you can select the Scope option that offers you a list of predefined scopes for your search. For example, you can limit your search only to the open files in your project or you can search in a class hierarchy.

Search in class hierarchy

If you work without tabs, the scope Recently Viewed Files or Recently Changed Files option might become quite useful. You can also create your own custom scope, click the Browse icon () to open the Scopes dialog.

Search in the specific file types

Use the File Mask option to narrow your search to a specific file type. You can select the existing file type from the list, add a new file type, or add an additional file mask syntax to search for file types with certain patterns.

In the Find in Files dialog, select the File Mask checkbox and from the list of file types, select the one you need.

File mask

IntelliJ IDEA limits its search to the specified type.

If you don't find the file type you need in the list, enter your file type in the File Mask field.

For example, use the following syntax to search only in gradle files: *.gradle .

Other wildcards besides * are supported. You can also specify several file types by separating them with a comma.

Replace the search string in a project

Press Ctrl+Shift+R to open the Replace in Path dialog.

In the top field, enter your search string. In the bottom field, enter your replacement string.

Replace in path dialog

For example, if you want to replace a variable name with a new name for a large project, use the replace in path instead of rename refactoring since your variable can appear in the config files as well.

Click one of the available Replace commands.

Work with the search results in the Find tool window

In the Find in Files dialog, click Open in Find Window to open the list of the search results in a separate window.

Using icons and context menu in the Find tool window, you can sort entries, exclude directories, navigate to the source code, and so on.

the Find tool window

Check the following popular options:

If you want to exclude a directory from the results, select a directory and from the context menu, select Exclude .

To locate the result of the search in the editor, use the Jump to Source option from the context menu.

To return back to the Find in Files dialog, click on the left toolbar.

To sort the search entries, select View Options | Sort Members Alphabetically in Show Options Menu ().

For more information on the options and icon references of the Find tool window, refer to the Find tool window reference section.

Читайте также: