Search in sources :

Example 16 with FileTemplateManager

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);
}
Also used : CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) Properties(java.util.Properties) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 17 with FileTemplateManager

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()]);
}
Also used : FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) ArrayList(java.util.ArrayList) Project(com.intellij.openapi.project.Project) EditFileTemplatesAction(com.intellij.ide.actions.EditFileTemplatesAction) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) NotNull(org.jetbrains.annotations.NotNull)

Example 18 with FileTemplateManager

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);
}
Also used : FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) ChooseTypeExpression(org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) GrMethod(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod) TextRange(com.intellij.openapi.util.TextRange) TypeConstraint(org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint) Project(com.intellij.openapi.project.Project) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Editor(com.intellij.openapi.editor.Editor) ParameterNameExpression(org.jetbrains.plugins.groovy.template.expressions.ParameterNameExpression)

Example 19 with FileTemplateManager

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();
        }
    }
}
Also used : TemplateImpl(com.intellij.codeInsight.template.impl.TemplateImpl) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) ReformatCodeProcessor(com.intellij.codeInsight.actions.ReformatCodeProcessor) SystemProperties(com.intellij.util.SystemProperties) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) OpenFileDescriptor(com.intellij.openapi.fileEditor.OpenFileDescriptor) PsiFile(com.intellij.psi.PsiFile) Editor(com.intellij.openapi.editor.Editor)

Example 20 with FileTemplateManager

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);
    }
}
Also used : Project(com.intellij.openapi.project.Project) FileTemplate(com.intellij.ide.fileTemplates.FileTemplate) FileTemplateManager(com.intellij.ide.fileTemplates.FileTemplateManager) File(java.io.File)

Aggregations

FileTemplateManager (com.intellij.ide.fileTemplates.FileTemplateManager)25 FileTemplate (com.intellij.ide.fileTemplates.FileTemplate)23 PsiFile (com.intellij.psi.PsiFile)7 Project (com.intellij.openapi.project.Project)6 Properties (java.util.Properties)6 ReformatCodeProcessor (com.intellij.codeInsight.actions.ReformatCodeProcessor)5 TemplateImpl (com.intellij.codeInsight.template.impl.TemplateImpl)5 Matcher (java.util.regex.Matcher)5 Pattern (java.util.regex.Pattern)5 IncorrectOperationException (com.intellij.util.IncorrectOperationException)4 IOException (java.io.IOException)4 VirtualFile (com.intellij.openapi.vfs.VirtualFile)3 File (java.io.File)3 NotNull (org.jetbrains.annotations.NotNull)3 Editor (com.intellij.openapi.editor.Editor)2 Module (com.intellij.openapi.module.Module)2 ConfigurationException (com.intellij.openapi.options.ConfigurationException)2 ArrayList (java.util.ArrayList)2 Nullable (org.jetbrains.annotations.Nullable)2 CreateClassAction (com.android.tools.idea.actions.CreateClassAction)1