IntelliJ Idea live templates

1 minute read

Live templates help to avoid manual typing the same (or similar) parts of the code. How it works? You have to simply start typing an abbreviation and hit Tab when you find the template you want.

You’ve got a lot of live templates to use out of the box, e.g.:

Builtin live templates

which look like:

  • sout:
    System.out.println($END$);
    
  • inn:
    if ($VAR$ != null) {
      $END$
    }
    

There are 2 builtin variables to use:

  • $END$ – used to set position of the cursor.
  • $SELECTION$ – replaced with selected part of the code (used when you wanted to surround code)

Besides them you can define your own variables to be used in templates like current class name, method name, timestamp and many others (see Intellij Docs)

Adding new custom template

You can easily add your custom templates by entering File->Settings->Editor->Live Templates(CTRL+ALT+S)

Next step is to create your new template group:

add-template-group

After that add new template:

add-new-template

Enter template abbreviation, description and template text:

new-template-form

Click Edit variables and bind variables to expressions:

edit-variables

The last step is defining context in which template should be proposed, e.g. Java:

define-context

Useful live templates

log

private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger($CLASS$.class);

Edit variables and set expression to className() for $CLASS$, check Skip if defined, then define new context (at the bottom) and select Java

test

@org.junit.Test
public void should$END$() throws Exception {
//given

//when

//then

}

epoch

$EPOCH$

where EPOCH = timestamp()

todo

//TODO: $END$ $DATE$ $USER

where $DATE = date(), $USER$ = user()

fixme

//FIXME: $END$ $DATE$ $USER

where $DATE = date(), $USER$ = user()

tr

@org.springframework.transaction.annotation.Transactional

trr

@org.springframework.transaction.annotation.Transactional(readOnly = true)

serialVersionUID

private static final long serialVersionUID = 1L;

rawtypes

@SuppressWarnings("rawtypes")

unchecked

@SuppressWarnings("unchecked")

unused

@SuppressWarnings("unused")

is

org.junit.Assert.assertThat($ACTUAL$, org.hamcrest.Matchers.is($END$));

Additionally select Use static import if possible

me

$USER

where $USER = user() (useful for creating liquibase changesets)

Importing

  1. Download intellij-live-templates.xml.
  2. Go to File->Settings->Editor->Live Templates(CTRL+ALT+S).
  3. Copy contents of live templates xml file to clipboard.
  4. Select or create some template group.
  5. Right click it and choose Paste(CTRL+V).

More resources