Search code examples
intellij-ideacode-completion

How do I create custom instance templates in IntelliJ IDEA?


Intellij supports 'instance templates' i.e. templates usable with expression followed by a period, such as cast, new etc. So MyClass.new expands to new MyClass(I) where I is the cursor.

Now I want to create my own template, expression.orElse which expands to:

Optional.ofNullable(expression).orElse(I)

I tried looking for options in Editor > Live Templates, but couldn't find anything relevant. Is this not possible in IntelliJ IDEA, or am I missing something?


Solution

  • These 'instance templates' are actually called postfix completion templates in IDEA.

    Starting with version 2019.2, custom postfix templates can also be created by going to Editor > General > Postfix Completion, as specified here and detailed in this blog post.

    For the asked case, the values would be:

    • Key: orElse
    • Minimum language leve: 8
    • Applicable expression types: non void
    • Value:
      Optional.ofNullable($EXPR$).orElse($END$)
      

    Variables:

    • $EXPR$: Replaced by the target expression
    • $END$: Location of cursor after substitution

    Enabling 'Apply to the topmost expression' disables the scope selection popup that appears on selecting the template.