Contributing a template to Eclipse via a Plugin to the Java Editor, but should vary based on the context

浪尽此生 提交于 2020-01-05 01:52:06

问题


So I wrote a plugin to contribute a template to the java editor in eclipse by using the extension "org.eclipse.ui.editors.templates". This just adds the template. That's not what I want. I want to replace the existing template with the new one, that too based on a condition.

For example, if the file name is "john.java", within that file if I type "sysout", I want my template to show up rather than the default one. Any ideas how I might be able to do this ?


回答1:


OK. I finally found a work around. JDT plugin does not offer an extension point for what I was trying to do. So I got the TemplateStore and modified it to suit my needs.

@Override
public void sessionStarted() {
    filterTemplates();
}

private void filterTemplates() {
    templateStore = getTemplateStore();
    file = getFileThatsVisibleInTheEditor();

    if (//file name is john.java) {
        deleteTemplate(templateStore, "org.eclipse.jdt.ui.templates.sysout");
    } else {
        deleteTemplate(templateStore, "com.eclipse.jdt.ui.templates.sysout");
    }

    try {
        templateStore.save();
    } catch (IOException e) {
    }
}

private void deleteTemplate(TemplateStore templateStore, String id) {
    TemplatePersistenceData templateData = templateStore.getTemplateData(id);
    if (templateData != null) {
        templateStore.delete(templateData);
    }
}

@Override
public void sessionEnded() {
    getTemplateStore().restoreDeleted();
}

private TemplateStore getTemplateStore() {
    if (templateStore == null) {
        final ContributionContextTypeRegistry registry = new ContributionContextTypeRegistry(JavaUI.ID_CU_EDITOR);
        final IPreferenceStore store = PreferenceConstants.getPreferenceStore();
        templateStore = new ContributionTemplateStore(registry, store, "org.eclipse.jdt.ui.text.custom_templates");
        try {
            templateStore.load();
        } catch (IOException e) {
        }
        templateStore.startListeningForPreferenceChanges();
    }
    return templateStore;
}

This whole this is written inside a class that extends IJavaCompletionProposalComputer. So every time you press Ctrl+Space, this code will be executed and your flavor of template will get executed.

In the above code, I have replaced the normal java sysout with the one that my plugin contributes based on the condition, so that at any point in time only one version of the 'sysout' is shown in the proposal. This is a hack, but I got my things done.



来源:https://stackoverflow.com/questions/29443263/contributing-a-template-to-eclipse-via-a-plugin-to-the-java-editor-but-should-v

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!