Search in sources :

Example 46 with Template

use of com.intellij.codeInsight.template.Template in project intellij-community by JetBrains.

the class GrAliasImportIntention method runTemplate.

private static void runTemplate(Project project, final GrImportStatement context, PsiMember resolved, final GroovyFileBase file, final List<UsageInfo> usages, GrImportStatement templateImport) {
    PostprocessReformattingAspect.getInstance(project).doPostponedFormatting();
    TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(templateImport);
    LinkedHashSet<String> names = getSuggestedNames(resolved, context);
    final PsiElement aliasNameElement = templateImport.getAliasNameElement();
    assert aliasNameElement != null;
    templateBuilder.replaceElement(aliasNameElement, new MyLookupExpression(resolved.getName(), names, (PsiNamedElement) resolved, resolved, true, null));
    Template built = templateBuilder.buildTemplate();
    final Editor newEditor = IntentionUtils.positionCursor(project, file, templateImport);
    final Document document = newEditor.getDocument();
    final RangeMarker contextImportPointer = document.createRangeMarker(context.getTextRange());
    final TextRange range = templateImport.getTextRange();
    document.deleteString(range.getStartOffset(), range.getEndOffset());
    final String name = resolved.getName();
    TemplateManager manager = TemplateManager.getInstance(project);
    manager.startTemplate(newEditor, built, new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            final GrImportStatement importStatement = ApplicationManager.getApplication().runReadAction(new Computable<GrImportStatement>() {

                @Nullable
                @Override
                public GrImportStatement compute() {
                    return PsiTreeUtil.findElementOfClassAtOffset(file, range.getStartOffset(), GrImportStatement.class, true);
                }
            });
            if (brokenOff) {
                if (importStatement != null) {
                    ApplicationManager.getApplication().runWriteAction(() -> importStatement.delete());
                }
                return;
            }
            updateRefs(usages, name, importStatement);
            ApplicationManager.getApplication().runWriteAction(() -> {
                final GrImportStatement context1 = PsiTreeUtil.findElementOfClassAtRange(file, contextImportPointer.getStartOffset(), contextImportPointer.getEndOffset(), GrImportStatement.class);
                if (context1 != null) {
                    context1.delete();
                }
            });
        }
    });
}
Also used : MyLookupExpression(com.intellij.refactoring.rename.inplace.MyLookupExpression) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) TextRange(com.intellij.openapi.util.TextRange) RangeMarker(com.intellij.openapi.editor.RangeMarker) Document(com.intellij.openapi.editor.Document) GrImportStatement(org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement) Template(com.intellij.codeInsight.template.Template) TemplateBuilderImpl(com.intellij.codeInsight.template.TemplateBuilderImpl) TemplateManager(com.intellij.codeInsight.template.TemplateManager) Editor(com.intellij.openapi.editor.Editor) Computable(com.intellij.openapi.util.Computable)

Example 47 with Template

use of com.intellij.codeInsight.template.Template in project intellij-community by JetBrains.

the class Replacer method checkSupportedReplacementPattern.

public static void checkSupportedReplacementPattern(Project project, ReplaceOptions options) throws UnsupportedPatternException {
    try {
        String search = options.getMatchOptions().getSearchPattern();
        String replacement = options.getReplacement();
        FileType fileType = options.getMatchOptions().getFileType();
        Template template = TemplateManager.getInstance(project).createTemplate("", "", search);
        Template template2 = TemplateManager.getInstance(project).createTemplate("", "", replacement);
        int segmentCount = template2.getSegmentsCount();
        for (int i = 0; i < segmentCount; ++i) {
            final String replacementSegmentName = template2.getSegmentName(i);
            final int segmentCount2 = template.getSegmentsCount();
            int j;
            for (j = 0; j < segmentCount2; ++j) {
                final String searchSegmentName = template.getSegmentName(j);
                if (replacementSegmentName.equals(searchSegmentName))
                    break;
                // Reference to
                if (replacementSegmentName.startsWith(searchSegmentName) && replacementSegmentName.charAt(searchSegmentName.length()) == '_') {
                    try {
                        Integer.parseInt(replacementSegmentName.substring(searchSegmentName.length() + 1));
                        break;
                    } catch (NumberFormatException ex) {
                    }
                }
            }
            if (j == segmentCount2) {
                ReplacementVariableDefinition definition = options.getVariableDefinition(replacementSegmentName);
                if (definition == null || definition.getScriptCodeConstraint().length() <= 2) /*empty quotes*/
                {
                    throw new UnsupportedPatternException(SSRBundle.message("replacement.variable.is.not.defined.message", replacementSegmentName));
                } else {
                    String message = ScriptSupport.checkValidScript(StringUtil.stripQuotesAroundValue(definition.getScriptCodeConstraint()));
                    if (message != null) {
                        throw new UnsupportedPatternException(SSRBundle.message("replacement.variable.is.not.valid", replacementSegmentName, message));
                    }
                }
            }
        }
        StructuralSearchProfile profile = StructuralSearchUtil.getProfileByFileType(fileType);
        assert profile != null;
        profile.checkReplacementPattern(project, options);
    } catch (IncorrectOperationException ex) {
        throw new UnsupportedPatternException(SSRBundle.message("incorrect.pattern.message"));
    }
}
Also used : FileType(com.intellij.openapi.fileTypes.FileType) IncorrectOperationException(com.intellij.util.IncorrectOperationException) Template(com.intellij.codeInsight.template.Template)

Example 48 with Template

use of com.intellij.codeInsight.template.Template in project intellij-community by JetBrains.

the class StringBasedPostfixTemplate method createTemplate.

public Template createTemplate(TemplateManager manager, String templateString) {
    Template template = manager.createTemplate("", "", templateString);
    template.setToReformat(shouldReformat());
    return template;
}
Also used : Template(com.intellij.codeInsight.template.Template)

Example 49 with Template

use of com.intellij.codeInsight.template.Template in project intellij-community by JetBrains.

the class JsonLiveTemplateTest method isApplicableContextUnderCaret.

private boolean isApplicableContextUnderCaret(@NotNull String text) {
    myFixture.configureByText(JsonFileType.INSTANCE, text);
    final Template template = createJsonTemplate("foo", "foo", "[42]");
    return TemplateManagerImpl.isApplicable(myFixture.getFile(), myFixture.getCaretOffset(), (TemplateImpl) template);
}
Also used : Template(com.intellij.codeInsight.template.Template)

Example 50 with Template

use of com.intellij.codeInsight.template.Template in project intellij-community by JetBrains.

the class GenerateMembersHandlerBase method runTemplates.

private static void runTemplates(final Project myProject, final Editor editor, final List<TemplateGenerationInfo> templates, final int index) {
    TemplateGenerationInfo info = templates.get(index);
    final Template template = info.getTemplate();
    final PsiElement element = info.getPsiMember();
    final TextRange range = element.getTextRange();
    WriteAction.run(() -> editor.getDocument().deleteString(range.getStartOffset(), range.getEndOffset()));
    int offset = range.getStartOffset();
    editor.getCaretModel().moveToOffset(offset);
    editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
    TemplateManager.getInstance(myProject).startTemplate(editor, template, new TemplateEditingAdapter() {

        @Override
        public void templateFinished(Template template, boolean brokenOff) {
            if (index + 1 < templates.size()) {
                ApplicationManager.getApplication().invokeLater(() -> new WriteCommandAction(myProject) {

                    @Override
                    protected void run(@NotNull Result result) throws Throwable {
                        runTemplates(myProject, editor, templates, index + 1);
                    }
                }.execute());
            }
        }
    });
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) TemplateEditingAdapter(com.intellij.codeInsight.template.TemplateEditingAdapter) TextRange(com.intellij.openapi.util.TextRange) Template(com.intellij.codeInsight.template.Template) Result(com.intellij.openapi.application.Result)

Aggregations

Template (com.intellij.codeInsight.template.Template)54 Editor (com.intellij.openapi.editor.Editor)20 TemplateBuilderImpl (com.intellij.codeInsight.template.TemplateBuilderImpl)19 Project (com.intellij.openapi.project.Project)17 TemplateManager (com.intellij.codeInsight.template.TemplateManager)15 TextRange (com.intellij.openapi.util.TextRange)15 TemplateEditingAdapter (com.intellij.codeInsight.template.TemplateEditingAdapter)12 PsiElement (com.intellij.psi.PsiElement)11 RangeMarker (com.intellij.openapi.editor.RangeMarker)9 IncorrectOperationException (com.intellij.util.IncorrectOperationException)9 NotNull (org.jetbrains.annotations.NotNull)5 MacroCallNode (com.intellij.codeInsight.template.impl.MacroCallNode)4 TextExpression (com.intellij.codeInsight.template.impl.TextExpression)4 Document (com.intellij.openapi.editor.Document)4 DartComponent (com.jetbrains.lang.dart.psi.DartComponent)4 Expression (com.intellij.codeInsight.template.Expression)3 SuggestVariableNameMacro (com.intellij.codeInsight.template.macro.SuggestVariableNameMacro)3 LocalQuickFixAndIntentionActionOnPsiElement (com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement)3 OpenFileDescriptor (com.intellij.openapi.fileEditor.OpenFileDescriptor)3 XmlTag (com.intellij.psi.xml.XmlTag)3