Tuesday, July 21, 2009

Eclipse: Adding Custom Code Templates Programmatically

Here comes the small tip how to add/remove the code templates programmatically.

Warning! This tip includes using the Eclipse internal API. It works fine in 3.5, but may not work in other versions!

First get access to the TemplateStore:
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jface.text.templates.persistence.TemplateStore;
public TemplateStore getCodeTemplateStore() {
return JavaPlugin.getDefault().getTemplateStore();

Delete template:
TemplateStore codeTemplateStore = getCodeTemplateStore();
TemplatePersistenceData templateData = codeTemplateStore.getTemplateData("template.id");
if (templateData != null) {
codeTemplateStore.delete(templateData );

Add new template:
String template = // template text
codeTemplateStore.add(new TemplatePersistenceData(new Template("template name", "Description", "java-members", template, true),true, "template.id"));

Save store:

No comments: