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:

“Surround With” menu

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 ➕

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$:

A Surround With “by lazy {}” template

This is basically it, really 😂 Now every time we have something like this

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

and now you have it wrapped like this

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 💪🏻