Search code examples
javaeclipsetemplatescontent-assist

Eclipse custom hotkey - print current line to standard out


Eclipse has a useful hotkey to assign current line to a local variable - when I type for instance:

Math.random()

and press ALT + SHIFT + L (Extract local variable), I can quickly change the line to

double random = Math.random();

I would like to use the same trick for printing it to std out, so that the Math.random() is being changed to:

System.out.println(Math.random());

Currently the fastet way to to this is to type syso and use content assist to use a template, but that requires manual copy pasting. Anyone knows a better way to do this?


Solution

  • Two options come to my mind to achieve your goal, but both of them require the selection of statement first.

    After you select statement, press CTRL+SPACE, then type syso and hit Enter. Selected statement will be placed inside System.out block:

    System.out.println(statement);
    

    Also you can prepare eclipse template (Window->Preference->Java->Editor->Content Assist->Templates), and give it some name:

    System.out.println(${line_selection});${cursor}
    

    After you select statement, press ALT+SHIFT+Z or select menu option Source->Surround With (also in context menu). Template you have created should be there so select it. Selected statement will be wrapped inside desired block of code.