Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Surround with method/function call in IDEA?

Is there any way to surround selection with an arbitrary method call?

Ex: let say, you have return dx; and you want to quickly transform it into return Math.abs(dx);

I'm aware of templates but then you have to hard code your surrounding(Math.abs in this case) and I'm looking for a generic solution, not bounded to any predefined method.

UPD 22.01.2019: As @de-li pointed out, the .arg postfix template is added. At the moment confirmed for Java. Feel free to vote for the Kotlin support: https://youtrack.jetbrains.com/issue/KT-29398

UPD: .arg template is available for Kotlin since 1.3.40-dev-568

like image 519
Ghedeon Avatar asked Oct 28 '15 15:10

Ghedeon


People also ask

How do I surround code with try catch in IntelliJ?

Simply select the code block to surround (don't forget to use Ctrl + W to increase the current selection) and then press Ctrl + Alt + T (or right-click the selection and select Surround with… from the menu). IntelliJ IDEA will show a list of options to choose from.

How do I refactor a method in IntelliJ?

Press Ctrl+Alt+M or from the main menu, select Refactor | Extract | Method. In the dialog that opens, configure a method options, such as visibility, parameters, and so on. You can also change a name of the method if you need. Click OK.


2 Answers

You could create a live template looking something like this:

$END$($SELECTION$) 

and then just select the text you want to wrap, hit Ctrl+Alt+T to show the suround with popup and select your template as illustrated in the image below:

enter image description here

That way you have generic template and you don't have to hardcode method name into it.

like image 98
Bohuslav Burghardt Avatar answered Sep 21 '22 06:09

Bohuslav Burghardt


Move to the end of the code and type '.arg', then press enter, IDE will add a pair of brackets to wrap the value and move the cursor to the beginning, then you can the method name you want.

like image 24
de li Avatar answered Sep 23 '22 06:09

de li