Search code examples
javaeclipsetimemacroskey-bindings

Keybinding keys to insert custom code Eclipse


How would I go about setting up a keybinding so when I press for example Ctrl+Shift+T in eclipse it surrounds the selected lines with a time measurer.

Like so:

1:

CODE
CODE
CODE

2: Select three lines and press CTRL+SHIFT+T

3:

long startTime = System.currentTimeMillis();
CODE
CODE
CODE
Print.pln("Time taken: " + (System.currentTimeMillis() - startTime) + "ms");

Solution

  • You can achieve this by using a template, for example:

    long ${newName} = System.currentTimeMillis();
    ${line_selection}
    Print.pln("Time taken: " + (System.currentTimeMillis() - ${newName}) + "ms");
    

    You can add this under Preferences->Java->Editor->Templates. Here you will have to give it a name, e.g. timer.

    To use it, select the code press CNTRL+SPACE twice, then select timer (or whatever name you gave to the template).

    Note that this will generate a name for the time variable.