use of com.intellij.ide.fileTemplates.FileTemplateManager in project qi4j-sdk by Qi4j.
the class AbstractCreateElementActionBase method createFromTemplateInternal.
protected static PsiFile createFromTemplateInternal(@NotNull PsiDirectory directory, @NotNull String name, @NotNull String fileName, @NotNull String templateName, @NonNls String... parameters) throws IncorrectOperationException {
// Load template
FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance();
FileTemplate template = fileTemplateManager.getJ2eeTemplate(templateName);
// Process template properties
Properties properties = new Properties(fileTemplateManager.getDefaultProperties());
JavaTemplateUtil.setPackageNameAttribute(properties, directory);
properties.setProperty(NAME_TEMPLATE_PROPERTY, name);
// Add parameters
for (int i = 0; i < parameters.length; i += 2) {
properties.setProperty(parameters[i], parameters[i + 1]);
}
// Create text from template with specified properties
String text;
try {
text = template.getText(properties);
} catch (Exception e) {
String message = "Unable to load template for " + fileTemplateManager.internalTemplateToSubject(templateName);
throw new RuntimeException(message, e);
}
// Serialized text to file
PsiManager psiManager = PsiManager.getInstance(directory.getProject());
PsiFileFactory fileFactory = PsiFileFactory.getInstance(directory.getProject());
PsiFile file = fileFactory.createFileFromText(fileName, text);
// Reformat the file according to project/default style
CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(psiManager);
codeStyleManager.reformat(file);
// Add newly created file to directory
return (PsiFile) directory.add(file);
}
use of com.intellij.ide.fileTemplates.FileTemplateManager in project intellij-community by JetBrains.
the class CreateFromTemplateGroup method getChildren.
@Override
@NotNull
public AnAction[] getChildren(@Nullable AnActionEvent e) {
if (e == null)
return EMPTY_ARRAY;
Project project = e.getProject();
if (project == null || project.isDisposed())
return EMPTY_ARRAY;
FileTemplateManager manager = FileTemplateManager.getInstance(project);
FileTemplate[] templates = manager.getAllTemplates();
boolean showAll = templates.length <= FileTemplateManager.RECENT_TEMPLATES_SIZE;
if (!showAll) {
Collection<String> recentNames = manager.getRecentNames();
templates = new FileTemplate[recentNames.size()];
int i = 0;
for (String name : recentNames) {
templates[i] = manager.getTemplate(name);
i++;
}
}
Arrays.sort(templates, (template1, template2) -> {
// java first
if (template1.isTemplateOfType(StdFileTypes.JAVA) && !template2.isTemplateOfType(StdFileTypes.JAVA)) {
return -1;
}
if (template2.isTemplateOfType(StdFileTypes.JAVA) && !template1.isTemplateOfType(StdFileTypes.JAVA)) {
return 1;
}
// group by type
int i = template1.getExtension().compareTo(template2.getExtension());
if (i != 0) {
return i;
}
// group by name if same type
return template1.getName().compareTo(template2.getName());
});
List<AnAction> result = new ArrayList<>();
for (FileTemplate template : templates) {
if (canCreateFromTemplate(e, template)) {
AnAction action = replaceAction(template);
if (action == null) {
action = new CreateFromTemplateAction(template);
}
result.add(action);
}
}
if (!result.isEmpty() || !showAll) {
if (!showAll) {
result.add(new CreateFromTemplatesAction(IdeBundle.message("action.from.file.template")));
}
result.add(Separator.getInstance());
result.add(new EditFileTemplatesAction(IdeBundle.message("action.edit.file.templates")));
}
return result.toArray(new AnAction[result.size()]);
}
use of com.intellij.ide.fileTemplates.FileTemplateManager in project intellij-community by JetBrains.
the class IntentionUtils method createTemplateForMethod.
public static void createTemplateForMethod(PsiType[] argTypes, ChooseTypeExpression[] paramTypesExpressions, PsiMethod method, PsiClass owner, TypeConstraint[] constraints, boolean isConstructor, @NotNull final PsiElement context) {
final Project project = owner.getProject();
PsiTypeElement typeElement = method.getReturnTypeElement();
ChooseTypeExpression expr = new ChooseTypeExpression(constraints, PsiManager.getInstance(project), context.getResolveScope(), method.getLanguage() == GroovyLanguage.INSTANCE);
TemplateBuilderImpl builder = new TemplateBuilderImpl(method);
if (!isConstructor) {
assert typeElement != null;
builder.replaceElement(typeElement, expr);
}
PsiParameter[] parameters = method.getParameterList().getParameters();
assert parameters.length == argTypes.length;
for (int i = 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
PsiTypeElement parameterTypeElement = parameter.getTypeElement();
builder.replaceElement(parameterTypeElement, paramTypesExpressions[i]);
builder.replaceElement(parameter.getNameIdentifier(), new ParameterNameExpression(null));
}
PsiCodeBlock body = method.getBody();
if (body != null) {
PsiElement lbrace = body.getLBrace();
assert lbrace != null;
builder.setEndVariableAfter(lbrace);
} else {
builder.setEndVariableAfter(method.getParameterList());
}
method = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(method);
Template template = builder.buildTemplate();
final PsiFile targetFile = owner.getContainingFile();
final Editor newEditor = positionCursor(project, targetFile, method);
TextRange range = method.getTextRange();
newEditor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset());
TemplateManager manager = TemplateManager.getInstance(project);
TemplateEditingListener templateListener = new TemplateEditingAdapter() {
@Override
public void templateFinished(Template template, boolean brokenOff) {
ApplicationManager.getApplication().runWriteAction(() -> {
PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
final int offset = newEditor.getCaretModel().getOffset();
PsiMethod method1 = PsiTreeUtil.findElementOfClassAtOffset(targetFile, offset - 1, PsiMethod.class, false);
if (context instanceof PsiMethod) {
final PsiTypeParameter[] typeParameters = ((PsiMethod) context).getTypeParameters();
if (typeParameters.length > 0) {
for (PsiTypeParameter typeParameter : typeParameters) {
if (CreateMethodFromUsageFix.checkTypeParam(method1, typeParameter)) {
final JVMElementFactory factory = JVMElementFactories.getFactory(method1.getLanguage(), method1.getProject());
PsiTypeParameterList list = method1.getTypeParameterList();
if (list == null) {
PsiTypeParameterList newList = factory.createTypeParameterList();
list = (PsiTypeParameterList) method1.addAfter(newList, method1.getModifierList());
}
list.add(factory.createTypeParameter(typeParameter.getName(), typeParameter.getExtendsList().getReferencedTypes()));
}
}
}
}
if (method1 != null) {
try {
final boolean hasNoReturnType = method1.getReturnTypeElement() == null && method1 instanceof GrMethod;
if (hasNoReturnType) {
((GrMethod) method1).setReturnType(PsiType.VOID);
}
if (method1.getBody() != null) {
FileTemplateManager templateManager = FileTemplateManager.getInstance(project);
FileTemplate fileTemplate = templateManager.getCodeTemplate(GroovyTemplates.GROOVY_FROM_USAGE_METHOD_BODY);
PsiClass containingClass = method1.getContainingClass();
LOG.assertTrue(!containingClass.isInterface() || GrTraitUtil.isTrait(containingClass), "Interface bodies should be already set up");
CreateFromUsageUtils.setupMethodBody(method1, containingClass, fileTemplate);
}
if (hasNoReturnType) {
((GrMethod) method1).setReturnType(null);
}
} catch (IncorrectOperationException e) {
LOG.error(e);
}
CreateFromUsageUtils.setupEditor(method1, newEditor);
}
});
}
};
manager.startTemplate(newEditor, template, templateListener);
}
use of com.intellij.ide.fileTemplates.FileTemplateManager in project intellij-community by JetBrains.
the class MavenUtil method runOrApplyFileTemplate.
private static void runOrApplyFileTemplate(Project project, VirtualFile file, String templateName, Properties properties, Properties conditions, boolean interactive) throws IOException {
FileTemplateManager manager = FileTemplateManager.getInstance(project);
FileTemplate fileTemplate = manager.getJ2eeTemplate(templateName);
Properties allProperties = manager.getDefaultProperties();
if (!interactive) {
allProperties.putAll(properties);
}
allProperties.putAll(conditions);
String text = fileTemplate.getText(allProperties);
Pattern pattern = Pattern.compile("\\$\\{(.*)\\}");
Matcher matcher = pattern.matcher(text);
StringBuffer builder = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(builder, "\\$" + matcher.group(1).toUpperCase() + "\\$");
}
matcher.appendTail(builder);
text = builder.toString();
TemplateImpl template = (TemplateImpl) TemplateManager.getInstance(project).createTemplate("", "", text);
for (int i = 0; i < template.getSegmentsCount(); i++) {
if (i == template.getEndSegmentNumber())
continue;
String name = template.getSegmentName(i);
String value = "\"" + properties.getProperty(name, "") + "\"";
template.addVariable(name, value, value, true);
}
if (interactive) {
OpenFileDescriptor descriptor = new OpenFileDescriptor(project, file);
Editor editor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true);
editor.getDocument().setText("");
TemplateManager.getInstance(project).startTemplate(editor, template);
} else {
VfsUtil.saveText(file, template.getTemplateText());
PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
if (psiFile != null) {
new ReformatCodeProcessor(project, psiFile, null, false).run();
}
}
}
use of com.intellij.ide.fileTemplates.FileTemplateManager in project intellij-community by JetBrains.
the class LightFileTemplatesTest method testSurviveOnProjectReopen.
public void testSurviveOnProjectReopen() throws Exception {
File foo = PlatformTestCase.createTempDir("foo");
Project reloaded = null;
final Project project = ProjectManager.getInstance().createProject("foo", foo.getPath());
try {
assertNotNull(project);
FileTemplateManager manager = FileTemplateManager.getInstance(project);
manager.setCurrentScheme(manager.getProjectScheme());
FileTemplate template = manager.getTemplate(TEST_TEMPLATE_TXT);
assertEquals(HI_THERE, template.getText());
String newText = "good bye";
template.setText(newText);
assertEquals(newText, manager.getTemplate(TEST_TEMPLATE_TXT).getText());
manager.saveAllTemplates();
PlatformTestUtil.saveProject(project);
closeProject(project);
reloaded = ProjectManager.getInstance().loadAndOpenProject(foo.getPath());
assertNotNull(reloaded);
manager = FileTemplateManager.getInstance(reloaded);
assertEquals(manager.getProjectScheme(), manager.getCurrentScheme());
//manager.setCurrentScheme(FileTemplatesScheme.DEFAULT);
//manager.setCurrentScheme(manager.getProjectScheme()); // enforce reloading
assertEquals(newText, manager.getTemplate(TEST_TEMPLATE_TXT).getText());
} finally {
closeProject(project);
closeProject(reloaded);
}
}
Aggregations