Допустим, у меня есть шаблон редактора (который вставляет произвольный фрагмент кода), определенный в моих настройках редактора.
Я хочу получить программный доступ к этому шаблону. Как мне это сделать?
Я знаю, что классы TemplateStore, TemplatePreferencesPage и TemplatePersistentData существуют, но мне не удалось объединить их во что-нибудь работающее.
Есть ли какой-нибудь пример кода, который позволил бы мне получить доступ к моему шаблону редактора через код Java?




Может быть, этот JavaPlugin класс (в пакете org.eclipse.jdt.internal.ui eclipse) может дать вам первую подсказку для подражания.
/**
* Returns the template store for the code generation templates.
*
* @return the template store for the code generation templates
* @since 3.0
*/
public TemplateStore getCodeTemplateStore() {
if (fCodeTemplateStore == null) {
IPreferenceStore store= getPreferenceStore();
boolean alreadyMigrated= store.getBoolean(CODE_TEMPLATES_MIGRATION_KEY);
if (alreadyMigrated)
fCodeTemplateStore= new ContributionTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY);
else {
fCodeTemplateStore= new CompatibilityTemplateStore(getCodeTemplateContextRegistry(), store, CODE_TEMPLATES_KEY, getOldCodeTemplateStoreInstance());
store.setValue(CODE_TEMPLATES_MIGRATION_KEY, true);
}
try {
fCodeTemplateStore.load();
} catch (IOException JavaDoc e) {
log(e);
}
fCodeTemplateStore.startListeningForPreferenceChanges();
// compatibility / bug fixing code for duplicated templates
// TODO remove for 3.0
CompatibilityTemplateStore.pruneDuplicates(fCodeTemplateStore, true);
}
return fCodeTemplateStore;
}
Оттуда вы можете найти какой-нибудь класс, использующий эту функцию:
НовыйASInterfaceWizard, похоже, нужен доступ к этим шаблонам кода:
private String resolveTemplate(String templateName) {
Template template = ASEditorPlugin.getDefault().getCodeTemplateStore().findTemplate(templateName);
if (template == null) {
showErrorBox("Could not resolve template (" + templateName +").");
return "";
}
// Create the template context
TemplateContext templeteContext = new TemplateContext(new ASContextType()) {
public TemplateBuffer evaluate(Template template) throws BadLocationException, TemplateException {
TemplateTranslator translator = new TemplateTranslator();
TemplateBuffer buffer = translator.translate(template);
getContextType().resolve(buffer, this);
return buffer;
}
public boolean canEvaluate(Template template) {
return true;
}
};
try {
return templeteContext.evaluate(template).getString();
} catch (BadLocationException e) {
logger.error("Couldnt evaluate template",e);
} catch (TemplateException e) {
logger.error("Couldnt evaluate template",e);
}
return "";
}
Используется так:
private static final String FILE_HEADER_TEMPLATE = "file_header";
// Header
String header = resolveTemplate(FILE_HEADER_TEMPLATE);
if (header.length() > 0) {
content.append(header + "\n");
}
Ну вот как я это сделал.
/**
* Get the Template Store of the JDT UI.
*
* @return the JDT template store
*/
private TemplateStore getTemplateStore() {
if (templateStore == null) {
System.out.println("templateStore is null - Creating a new one");
final ContributionContextTypeRegistry registry = new ContributionContextTypeRegistry(JavaUI.ID_CU_EDITOR);
final IPreferenceStore store = PreferenceConstants.getPreferenceStore();
templateStore = new ContributionTemplateStore(registry, store, TEMPLATES_KEY);
try {
templateStore.load();
} catch (IOException e) {
WSConsole.e(e);
}
templateStore.startListeningForPreferenceChanges();
}
return templateStore;
}
Вышеупомянутый метод возвращает TemplateStore. Вы используете магазин для добавления, удаления, поиска шаблонов.
private void filterTemplates() {
templateStore = getTemplateStore();
deleteTemplate(templateStore, "org.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);
}
}
Вот как выполнять операции с TemplateStore. Если вы хотите найти шаблон, имя, описание шаблона, вы можете получить это, получив объект Template из TemplateStore. Если вы хотите найти идентификатор шаблона, вы можете получить его из объекта TemplatePersistantData.