以编程方式添加Java代码模板 [英] Add Java code template programmatically
问题描述
我喜欢Eclipse允许我使用Tab键在方法调用中跳转参数。我想让我的插件提供类似的功能。准确地说,我将一些文本注入编辑器,我想强调具体的语法,让程序员使用Tab键跳转到下一个匹配项。
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.[?]
我会将其注入编辑器,想要 [?]
被突出显示并准备修改(用户可能键入 length()
)。此外,如果有更多的 [?]
碎片,我希望用户使用Tab移动到下一个。
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?
更新:
我发现两个链接这可能是有用的,虽然我仍然无法提出解决方案。
I found two links that might be useful, although I am still not able to come up with a solution.
link two
推荐答案
样本处理程序代码:
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);
结果:
我建议你使用 org.eclipse.jdt.ui.javaCompletionProposalComputer
扩展名。它允许你可以提供模板更合法的方式。
I suggest you use org.eclipse.jdt.ui.javaCompletionProposalComputer
extension. It allows you can contribute Template more legal way.
在我的代码中,有黑客,因为没有办法得到 ISourceViewer
合法。我知道 ISourceViewer
是 ITextTargetOperation
本身,但它不是API(非法铸造)。并且模板旨在设计为由 TemplateCompletionProcessor
或 TemplateCompletionProposalComputer
使用。
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
.
这篇关于以编程方式添加Java代码模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!