14

How can add new custom functions for Live Templates in Idea Intellij.

For example i need a custom function which can convert a live template variable from Camel Case to Spaced. i.e in Live Template on variable has to be inserted at multiple places with & without space.

Eg. "MyVar" and "My Var". So i want to insert an expression to convert 'MyVar' to 'My Var'.

No expression available by default can be used for this.

Thanks.

Aman
  • 916
  • 11
  • 16

2 Answers2

17

There is OpenAPI for providing Live Template functions. One can create IntelliJ IDEA plug-in that will add more functions.

See the Macro abstract class. Plug-in should define extension point, like this one:

<liveTemplateMacro implementation="com.intellij.codeInsight.template.macro.CapitalizeMacro"/>

Search IntelliJ IDEA Community code base for sample implementations.

CrazyCoder
  • 389,263
  • 172
  • 990
  • 904
0

Thanks @CrazyCoder answer , I will show my code how I added the custom expression to live templates.

  1. Creating a Plugin Gradle Project https://plugins.jetbrains.com/docs/intellij/creating-plugin-project.html

If you have error like Could not resolve all files for configuration ':classpath'.

you should open Preferences -> Build,Execution,Deployment -> Build Tools -> Gradle select Gradle JVM to you have installed version

  1. Create your own class like this:
package com.xxxx.yourPackage;

import com.intellij.codeInsight.template.*;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class MyLiveTemplateExpression extends Macro {


    @Override
    public @NonNls String getName() {
        return "MyLiveTemplateExpression";
    }

    @Override
    public @Nullable Result calculateResult(Expression @NotNull [] params, ExpressionContext context) {
        return new TextResult("测试自己的宏");
    }
}

In this code the method getName will return a string name which will be shown in live-templates enter image description here

  1. edit plugin.xml add liveTemplateMacro tag into extensions tag, like this:
<liveTemplateMacro implementation="com.xxxx.yourPackage.yourClass"/>

In my case implementation value is com.xxxx.cusomLiveTemplate.MyLiveTemplateExpression

  1. Select right sidebar Gradle to build jar enter image description here

  2. open Perference -> plugins click setting icon and choose install from disk to install plugin

  3. you can use this expression now

Because I am a frontend developer, I do not how to write java code... so the code is not strong, I really hope some javaer can edit this answer or tell me how to write more better!

Sorry for my poor English, Hope someone can edit it and make it more easy to understand

mqliutie
  • 377
  • 2
  • 17