I have created a code template to add a logger and the corresponding import:

${:import(org.apache.log4j.Logger)}
private static final Logger logger = Logger.getLogger(${enclosing_type}.class);

If I add this now, the logger always starts at the beginning of the line, even if my cursor is already indented. Is there a way to to force the placement at the position of the cursor?

This is a screenshot to show what I mean:

enter image description here

====>>>>

enter image description here

Edit: The answer from Grove helped in this specific case. But how about this example? I also want to add a comment to the logger. If I define the template like this in the same line, the logger actually apears in the same line as the comment.

${:import(org.apache.log4j.Logger)}
/**
 *  Logger
 */ private static final Logger logger = Logger.getLogger(${enclosing_type}.class);
有帮助吗?

解决方案 2

I don't think you need to concentrate on templates for this. You can use Formatter for this.

Create your own formatter in Windows > Preferences > Java > Code Style > Formatter and enable Save Actions in Windows > Preferences > Java > Editor > Save Actions (Select Format Source code and Format all lines options) and here you choose your formatter created before.

Once you insert the logger template editor becomes dirty then save the editor(press Ctrl + S) then automatic indentation will happen as per the settings in formatter.

Refer this and this for formatter creation. In Indentation tab use the number of space you like. I used Tab Policy = Spaces only and Indentation size = 4.

其他提示

Yes there is, do not add a new line between the import and the logger definition:

${:import(org.apache.log4j.Logger)}private static final Logger logger = Logger.getLogger(${enclosing_type}.class);

Side-note: If needed, you can also position the cusrsor in your template with the ${cursor} variable

EDIT AFTER QUESTION UPDATE: The same thing applies, the import variable does not have to be the first in the pattern, it can be anywhere and it will be evaluated nonetheless:

/**
 *  Logger
 */
${:import(org.apache.log4j.Logger)}private static final Logger logger = Logger.getLogger(${enclosing_type}.class);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top