Getting started with IntelliJ IDEA Live Templates

posted by Roberto Cortez on
tags: , ,

Do you find yourself writing the same code over and over again? Maybe you’re already familiar with IntelliJ Live Templates feature. If that’s the case don’t go away. I’m going to demonstrate how to use them, but also the most interesting part is how to create your own Live Templates that can help you on your everyday coding.

For those not familiar with Live Templates, this feature allows you to quickly insert code fragments in your source code files and have the ability to replace or auto-complete sections of the template based on the current code context. IntelliJ already has a lot of templates that you can use right away after installing the IDE. You can have a look into the templates by using the shortcut CTRL+J/CMD+J:

Live Templates Popup

You get a list of the Live Templates that can be applied in the current context. The context is related with the file type you are editing (Java, SQL, XML, HTML, etc.), and also with the section itself (inside a method, field declaration, in the comments, etc). Let’s try one of the Live Templates I use the most, iterate an array. Did you notice the abbreviation on the left side of the Live Template popup? You can use it instead of using the popup shortcut. Just type iter followed by TAB key (do it inside the main method):

Iteration Expansion

The Live Template gets expanded to the Java 5 for each loop and IntelliJ suggests you the args array from the main method in the iteration plus the element type being iterated. You can pick other arrays available in the context and the code will automatically adjust to your choice (look at the red square around the args, it can auto complete to other arrays using CTRL+SPACE). Pretty cool!

Other notable Live Templates that I find pretty useful:

AbbreviationGenerated Code
psvmpublic static void main(String[] args) {}
psfspublic static final String
psfpublic static final
soutvSystem.out.println("var = " + $var);
ifnif ($var == null) {}
innif ($var != null) {}

Try to explore others that suit your programming style. Remember, Live Templates change with the file type you are editing. If you type udp in a SQL file and press TAB the abbreviation gets expanded to update set = where ;.

The real power is IntelliJ ability to create and customise your own code fragments. Lacking ideas? How about List<String> strings = new ArrayList<String>();? You type that a lot right? Well, maybe not with the String type, but that’s just an example. We’re going to create a Live Template for it where you can pick the type of the elements in the List. Go to IntelliJ Settings CTRL+ALT+S/CMD+, and search for Live Templates. You should get the following screen:

Live Templates Settings

We can now add a new Live Template by pressing the + on the right upper corner of the screen. We now need to add an abbreviation, a description, the template text itself and pick the applicable contexts.

Template TextList<$TYPE$> $VAR$ = new ArrayList<$TYPE$>();
ApplicableJava: statement, declaration

Add Live Template

The $TYPE$ and $VAR$ are variables that you can replace on the Live Template generation using IntelliJ pre-defined functions. Go to Edit Variables screen and you should get a screen like this:

Edit variables Live Template

So expectedType() replaces the $TYPE$ variable with a class type with the default value of String and suggestVariableName() replace the $VAR$ variable with an auto suggestion for the variable name where the default value is list. Take a look into IntelliJ help and see which other predefined functions are available for you to use. You can even use Groovy code!

Now you can type ls in the editor and expand it with TAB. You will get:

List Live Template

You can auto-complete and replace String by another type. Notice how the rest of the template adjusts to your pick:

List Live Template Edit

Note: If you’re using Java 7 or higher you can get rid of the generic type declaration on the right hand side of the template. I’m still working in a couple of projects that use Java 6, so I need it this way.

Now you just have to think on the code you type all the time and convert it to a Live Template and save precious time typing it! How about a template to create the Log instance to perform logging? You’re also going to need template log methods like sout to output""), log.error("") and so on. Try them out!

Feel free to share your Live Templates :)

Share with others!
  • Twitter
  • Facebook
  • LinkedIn
  • Google Plus
  • Reddit
  • Add to favorites
  • Email
  • RSS

Comments ( 8 )

  1. Replyjnuno

    Hi Cortez,

    Glad to see your blog taking shape!

    Some small corrections:
    1) In the table of notable Live Templates you have psfs twice and the 2nd is wrong.
    2) When you say “How about List strings = new ArrayList();? You type that a lot right?” you forgot the type signature.
    3) The template you recommend to solve 2) could make use of the diamond operator.

    Hope that helps. Thank you for your community contributions.

    • ReplyRoberto Cortez

      Hi João! Thank you so much for your comment and your support. Fixed #1 and #2 and #3 unfortunately I’m still using java 6 in some of my project so I need the template that way, but I added a note about that. Thank you for findings!

      Cya in next Coimbra JUG :)

  2. Replypanda

    nice article!

  3. ReplyThyle

    Thanks for the article, I definitely enjoyed it !

    I did few changes to your template, if it could inspire someone the same way yours inspire me :

    List $var$ = new ArrayList($params$);

    $params$ : no default value, easy to reach since you only have to press tab
    $END$ : this one can’t have a value, but by pressing tab you’ll be ready to write an other line of code ! I think it’s more convenient than using my mouse or ctrl+maj+enter.

    I also use this one for my tests :

    public void $METHODE_NAME$_when$STATE_UNDER_TEST$_should$EXPECTED_BEHAVIOR$() throws Exception{

    I like when my tests’ name are sentences, and with this template it doesn’t take me an additional effort.

    • ReplyRoberto Cortez

      Hi Thyle,

      Great! Thank you for your contribution. I usually use cmd + shit + enter (complete current statement) to switch line, but that way it’s more efficient. I’ve just updated my template :)

  4. Replyvivian8725118

    Hi,I have a question there.
    I want to know how to generate code like getters and setters according to the variables that have already existed.

    • ReplyRoberto Cortez

      Hi Vivian,

      Sorry for the late reply.

      Just type hit CTRL + N in a Mac or ALT + INSERT I believe for Windows. This will bring the Generate menu, and you can pick to generate getters and setters. An alternative is to hit CMD / CTRL + SHIFT + A and type generate. This needs to be done in a context of a Java source file.


Leave a reply

Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>