java代码模板,以编程方式添加Java代码模板

I like when Eclipse lets me jump between parameters in a method call using a Tab key. I would like my plugin to provide a similar functionality. To be precise, I am injecting some piece of text into the editor and I would like to highlight specific syntax and let the programmer jump to the next match using the Tab key.

Here is an example. Lets suppose I dynamically created the following snippet:

String a = "bogus string";

int i = a.[?]

I will inject that into the editor and I would like that [?] is highlighted and ready for modification (user might type length()). Moreover, if there is more [?] fragments, I would like user to use Tab to move to the next one.

After researching a bit, I found that it might be done using templates. However, I can't find any relevant examples on the Web. Does anybody have experience with this?

UPDATE:

I found two links that might be useful, although I am still not able to come up with a solution.

解决方案

Sample Handler Codes:

AbstractTextEditor activeEditor =

(AbstractTextEditor) HandlerUtil.getActiveEditor(event);

ISourceViewer sourceViewer =

(ISourceViewer) activeEditor.getAdapter(ITextOperationTarget.class);

Point range = sourceViewer.getSelectedRange();

// You can generate template dynamically here!

Template template = new Template("sample",

"sample description",

"no-context",

"private void ${name}(){\r\n" +

"\tSystem.out.println(\"${name}\")\r\n"

+ "}\r\n", true);

IRegion region = new Region(range.x, range.y);

TemplateContextType contextType = new TemplateContextType("test");

TemplateContext ctx =

new DocumentTemplateContext(contextType,

sourceViewer.getDocument(),

range.x,

range.y);

TemplateProposal proposal

= new TemplateProposal(template, ctx, region, null);

proposal.apply(sourceViewer, (char) 0, 0, 0);

Result:

8rASi.png

I suggest you use org.eclipse.jdt.ui.javaCompletionProposalComputer extension. It allows you can contribute Template more legal way.

In my codes, there are hacks since there is no way to get ISourceViewer legally. I know ISourceViewer is ITextTargetOperation itself, but it is not API(Illegal Casting). And Template is intended to designed to be used by TemplateCompletionProcessor or TemplateCompletionProposalComputer.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值