Tips & Tricks

Creating live templates from… templates

Sometimes I find myself writing repetitive code constructs without being able to extract common code due to Java syntax hmm… let’s call them peculiarities. ‘Sounds like a job for a live template’, I think, and I simply create it. Here’s how. The documentation has it too, but a good example never hurts.

Let’s suppose you have read/write synchronization in your project, and from time to time you need to wrap a bunch of statements in, say, a read action. This involves putting them into a Runnable and giving the latter to some runReadAction method. Do you still do this manually? You don’t need to, IntelliJ IDEA will help you!

First, find an existing code which already invokes the read action and select it:

Go to Tools menu and choose Save as Live Template there:

You’ll see a typical Edit Live Template dialog with the text you’ve selected. Note that all the class references are qualified there and Shorten FQ names checkbox is on, so the mentioned classes will remain the same no matter where you choose to insert it.

What we want to keep is the external syntax: the method call and the runnable. So remove everything inside the run() method braces and replace it with a $SELECTION$ on a single line. It means that you may select something and it’ll be wrapped in this particular construct.

Enter some abbreviation to easily invoke it each time, and some description (optional, but useful). Finally, the formatting looks not quite pretty, so turn on the Reformat according to style checkbox.

That’s all! Click OK and start using it. Find a fragment you want to wrap into a read-action, select it and invoke Surround With… action (Ctrl+Alt+T). You’ll see the read action template in the list:

Select it and the read action is in there:

image description