Eclipse Code Templates: insert clipboard?
I have begun using Eclipse code templates and am loving 'em! But for existing code they are a bit hard to use. This is easiest with an example.
I have a pre-existing bit of code and I want to wrap it in a try-catch block. Currently I create the try-catch block from the template and then cut-paste the code I want inside the try block.
What I want is a way to cut the code and have it insert inside the try template automatically, i.e. using something like a {clipboard} tag inside the te开发者_如何转开发mplate code. Is there a way to accomplish this in Eclipse?
In general the best way to learn how to do these types of things is look at the existing templates. Especially since the names of the variables might change. Use ${line_selection} or ${word_selection} in your template. It has been a while since you asked this question, and now there is a pre-built try catch block, just hightlight the code you want to wrap, hit Ctrl-space
, and type try
and hit enter
. As you type your code gets deleted but when you hit enter it comes back wrapped in the template.
There are other good uses for a ${clipboard} variable but it's 2011 and I don't think one exists yet.
You can use a variable of type "Selection". Create the template code then go to the Variables tab and change your variable's type.
To use, select the code that will be the body of the try-block. Hit ctrl-enter. Select template.
The template code would look something like:
try
$sel$
catch (exception e) {
// TODO blah
}
I was asking me the same thing.
The request for a ${clipboad} variable is opened in Eclipse Bug 198886.
${line_selection} and ${word_selection} are good possibilities.
Other possibilities:
You can also use ${cursor} to place the cursor where you want. After that you just have to paste your clipboard content (CTRL-V)
Here my favorite: use ${Default Value} or just ${} in combination with ${word_selection}
Here my template:
${:import(myapp.shared.core.security.DefaultPermission, myapp.shared.core.security.DefaultPermission.PermissionRight)}setVisiblePermission(new DefaultPermission(${70L}, PermissionRight.READ));
Result of this template:
I just have to paste an other Long value from the clipboard to replace 70L (which is in my case a good default value).
Other example from Eclipse (Button SWT Statements):
${buttonType:newType(org.eclipse.swt.widgets.Button)} ${button:newName(org.eclipse.swt.widgets.Button)}= new ${buttonType}(${parent:var(org.eclipse.swt.widgets.Composite)}, ${style:link(SWT.PUSH, SWT.TOGGLE, SWT.RADIO, SWT.CHECK, SWT.FLAT)});
${button}.setLayoutData(new ${type:newType(org.eclipse.swt.layout.GridData)}(SWT.${horizontal:link(BEGINNING, CENTER, END, FILL)}, SWT.${vertical:link(CENTER, TOP, BOTTOM, FILL)}, ${hex:link(false, true)}, ${vex:link(false, true)}));
${button}.setText(${word_selection}${});
${imp:import(org.eclipse.swt.SWT)}${cursor}
They use ${word_selection}${} to achieve the same result.
精彩评论