Search code examples
javatemplatesintellij-ideaideshortcut

Is it possible to add own shortcuts and templates in Intellij?


Say I have this static method

public static void doSomething () { //do stuff... }

And I need to use it on several different codes I'm writing.

Is there a way to save it in IntelliJ, so that next time I don't need to write it from the beginning but rather choose a shortcut? Something similar to what it does with the setter and the getter methods, which are automatically written by the IDE itself.

Thanks


Solution

  • To begin with, let's make a simple example, for example, the hello method. Go to Settings -> Editor - > Live Templates. Here you can view ready-made groups of templates and create your own by clicking on the plus sign on the right side of the panel. You can also create a separate template, then it will be added to the user group. After clicking, you will see a window at the bottom where you need to enter an abbreviation, descriptions, and the actual text of the template. There will also be a warning label "No applicable context" and a Define button next to it, clicking on which we will see a list of possible contexts — HTML, XML, Java, Javascript, CSS, and so on. Some have sub-items, for example in Java it is possible to use a template in a method, in a comment, at the class level, somewhere else, or everywhere at once. Choose the entire Java package as an example.

    As an abbreviation, we will write hello, as a text, here is a line like this:

    public static void hello() {
         System.out.println("Hello")
        }
    

    Click OK, after Apply and you can check. Create a class with any name, write hello inside, press TAB and voila — we have this method