In one of my previous posts I wrote about one of my favorite features of IntelliJ IDEA/AS: Live Templates. “Surround With” is a sort of LT’s cousin.
When you want to wrap a piece of code with a specific snippet, you select the code and hit the “Surround With” shortcut. On Mac you can access it as Option+Cmd+T
(on Win is Ctrl+Alt+T
) and you get a menu like this:
![](https://ivanmorgillo.com/wp-content/uploads/2020/09/image.png)
These are great if you find yourself needing to wrap a block in an if-else
or a try/catch
, but in my daily I often need something more Kotlin specific and that’s why I looked up some documentation and I started creating my own “Surround With” shortcuts! 😃
How to create a “Surround With”
It turns out “Surround With” are just a special type of “Live Template”. In IDEA, open Preferences, go to Live Templates and click ➕
![](https://ivanmorgillo.com/wp-content/uploads/2020/09/image-1-1024x458.png)
Now the question is
How we specify that the template has to go _around_ the selection?
Everything is done automatically by IDEA if we name the selected text placeholder as `$SELECTION$:
![](https://ivanmorgillo.com/wp-content/uploads/2020/09/image-3-1024x453.png)
This is basically it, really 😂 Now every time we have something like this
![](https://ivanmorgillo.com/wp-content/uploads/2020/09/image-6.png)
and we want to postpone the creation of the value until necessary using by lazy
you can select the code, hit the shortcut and see
![](https://ivanmorgillo.com/wp-content/uploads/2020/09/image-4.png)
and now you have it wrapped like this
![](https://ivanmorgillo.com/wp-content/uploads/2020/09/image-7.png)
Sweet! 😃
More templates
Some of my favorite templates are
viewModelScope.launch { $SELECTION$ }
withContext(Dispatchers.IO) { $SELECTION$ }
Timber.d($SELECTION)
Let me know what are your favorite “Surround With” templates that make your coding life easier 😃
Happy coding 💪🏻
0 responses to “IntelliJ IDEA / Android Studio Tricks: Surround With”