47

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

Ghedeon
  • 1,643
  • 1
  • 18
  • 30

3 Answers3

80

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.

Bohuslav Burghardt
  • 33,626
  • 7
  • 114
  • 109
  • 3
    Neat! Similar to existing ```(expr)``` but you nailed it with ```$END$``` in front. Now, the real question is how did you make this beautiful gif? :) – Ghedeon Oct 29 '15 at 14:20
  • @Ghedeon [ScreenToGif](https://screentogif.codeplex.com/). Really nice app. Just gotta find something like this for Mac :) – Bohuslav Burghardt Oct 29 '15 at 14:24
  • 1
    that would be nice if we could use the `.par` post fix feature and move the cursor to the left – Kirill Kulakov Aug 08 '16 at 11:51
  • 1
    Is there a way to create the selection (the thing you want to surround) using the same kind of pop-up that happens when you extract a variable (Ctrl+Alt+V) or extract a method (Ctrl+Alt+M) etc? It's making that initial selection by hand that's killing me. – Dmitry Minkovsky Jun 22 '19 at 12:13
  • @arekolek's answer to use ⌥+⌘+J for Surround With Live Template requires less key presses (no pressing up twice for me at least since it's the only live template I have). – Graeme Moss May 29 '20 at 14:19
38

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.

de li
  • 882
  • 1
  • 13
  • 25
17

To add to the answer above:

  1. Go to Android Studio > Preferences.
  2. Choose Editor > Live Templates in the navigation.
  3. Expand the surround group of live templates.
  4. Select P (Surround with()) and click Duplicate on the right.
  5. Put F as Abbreviation, Surround with function call as Description and $END$($SELECTION$) as Template text.
  6. Click to Change the Applicable scope and select Expression, String, and Other under Java.

Now it's possible to just select something, hit ++J (Surround with Live Template) and the new live template is first on this list, so just hit enter.

arekolek
  • 9,128
  • 3
  • 58
  • 79