Search in sources :

Example 1 with TemplateState

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

the class PyIntroduceTestCase method doTestInplace.

protected void doTestInplace(@Nullable Consumer<IntroduceOperation> customization) {
    String name = getTestName(true);
    myFixture.configureByFile(name + ".py");
    final boolean enabled = myFixture.getEditor().getSettings().isVariableInplaceRenameEnabled();
    try {
        TemplateManagerImpl.setTemplateTesting(myFixture.getProject(), myFixture.getTestRootDisposable());
        myFixture.getEditor().getSettings().setVariableInplaceRenameEnabled(true);
        IntroduceHandler handler = createHandler();
        final IntroduceOperation introduceOperation = new IntroduceOperation(myFixture.getProject(), myFixture.getEditor(), myFixture.getFile(), "a");
        introduceOperation.setReplaceAll(true);
        if (customization != null) {
            customization.consume(introduceOperation);
        }
        handler.performAction(introduceOperation);
        WriteCommandAction.runWriteCommandAction(myFixture.getProject(), () -> {
            TemplateState state = TemplateManagerImpl.getTemplateState(myFixture.getEditor());
            assert state != null;
            state.gotoEnd(false);
        });
        myFixture.checkResultByFile(name + ".after.py", true);
    } finally {
        myFixture.getEditor().getSettings().setVariableInplaceRenameEnabled(enabled);
    }
}
Also used : IntroduceHandler(com.jetbrains.python.refactoring.introduce.IntroduceHandler) IntroduceOperation(com.jetbrains.python.refactoring.introduce.IntroduceOperation) TemplateState(com.intellij.codeInsight.template.impl.TemplateState)

Example 2 with TemplateState

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

the class IntroduceHandler method performAction.

public void performAction(IntroduceOperation operation) {
    final PsiFile file = operation.getFile();
    if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) {
        return;
    }
    final Editor editor = operation.getEditor();
    if (editor.getSettings().isVariableInplaceRenameEnabled()) {
        final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor());
        if (templateState != null && !templateState.isFinished()) {
            return;
        }
    }
    PsiElement element1 = null;
    PsiElement element2 = null;
    final SelectionModel selectionModel = editor.getSelectionModel();
    boolean singleElementSelection = false;
    if (selectionModel.hasSelection()) {
        element1 = file.findElementAt(selectionModel.getSelectionStart());
        element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
        if (element1 instanceof PsiWhiteSpace) {
            int startOffset = element1.getTextRange().getEndOffset();
            element1 = file.findElementAt(startOffset);
        }
        if (element2 instanceof PsiWhiteSpace) {
            int endOffset = element2.getTextRange().getStartOffset();
            element2 = file.findElementAt(endOffset - 1);
        }
        if (element1 == element2) {
            singleElementSelection = true;
        }
    } else {
        if (smartIntroduce(operation)) {
            return;
        }
        final CaretModel caretModel = editor.getCaretModel();
        final Document document = editor.getDocument();
        int lineNumber = document.getLineNumber(caretModel.getOffset());
        if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) {
            element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
            element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
        }
    }
    final Project project = operation.getProject();
    if (element1 == null || element2 == null) {
        showCannotPerformError(project, editor);
        return;
    }
    element1 = PyRefactoringUtil.getSelectedExpression(project, file, element1, element2);
    final PyComprehensionElement comprehension = PsiTreeUtil.getParentOfType(element1, PyComprehensionElement.class, true);
    if (element1 == null || comprehension != null) {
        showCannotPerformError(project, editor);
        return;
    }
    if (singleElementSelection && element1 instanceof PyStringLiteralExpression) {
        final PyStringLiteralExpression literal = (PyStringLiteralExpression) element1;
        // Currently introduce for substrings of a multi-part string literals is not supported
        if (literal.getStringNodes().size() > 1) {
            showCannotPerformError(project, editor);
            return;
        }
        final int offset = element1.getTextOffset();
        final TextRange selectionRange = TextRange.create(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd());
        final TextRange elementRange = element1.getTextRange();
        if (!elementRange.equals(selectionRange) && elementRange.contains(selectionRange)) {
            final TextRange innerRange = literal.getStringValueTextRange();
            final TextRange intersection = selectionRange.shiftRight(-offset).intersection(innerRange);
            final TextRange finalRange = intersection != null ? intersection : selectionRange;
            final String text = literal.getText();
            if (getFormatValueExpression(literal) != null && breaksStringFormatting(text, finalRange) || getNewStyleFormatValueExpression(literal) != null && breaksNewStyleStringFormatting(text, finalRange) || breaksStringEscaping(text, finalRange)) {
                showCannotPerformError(project, editor);
                return;
            }
            element1.putUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE, Pair.create(element1, finalRange));
        }
    }
    if (!checkIntroduceContext(file, editor, element1)) {
        return;
    }
    operation.setElement(element1);
    performActionOnElement(operation);
}
Also used : CaretModel(com.intellij.openapi.editor.CaretModel) TextRange(com.intellij.openapi.util.TextRange) Document(com.intellij.openapi.editor.Document) TemplateState(com.intellij.codeInsight.template.impl.TemplateState) Project(com.intellij.openapi.project.Project) SelectionModel(com.intellij.openapi.editor.SelectionModel) Editor(com.intellij.openapi.editor.Editor)

Example 3 with TemplateState

use of com.intellij.codeInsight.template.impl.TemplateState in project kotlin by JetBrains.

the class KotlinInplaceVariableIntroducer method runWriteActionAndRestartRefactoring.

protected final void runWriteActionAndRestartRefactoring(final Runnable runnable) {
    final Ref<Boolean> greedyToRight = new Ref<Boolean>();
    new WriteCommandAction(myProject, getCommandName(), getCommandName()) {

        @Override
        protected void run(@NotNull Result result) throws Throwable {
            PsiDocumentManager.getInstance(myProject).commitDocument(myEditor.getDocument());
            ASTNode identifier = myDeclaration.getNode().findChildByType(KtTokens.IDENTIFIER);
            if (identifier != null) {
                TextRange range = identifier.getTextRange();
                RangeHighlighter[] highlighters = myEditor.getMarkupModel().getAllHighlighters();
                for (RangeHighlighter highlighter : highlighters) {
                    if (highlighter.getStartOffset() == range.getStartOffset()) {
                        if (highlighter.getEndOffset() == range.getEndOffset()) {
                            greedyToRight.set(highlighter.isGreedyToRight());
                            highlighter.setGreedyToRight(false);
                        }
                    }
                }
            }
            runnable.run();
            TemplateState templateState = TemplateManagerImpl.getTemplateState(InjectedLanguageUtil.getTopLevelEditor(myEditor));
            if (templateState != null) {
                myEditor.putUserData(INTRODUCE_RESTART, true);
                templateState.cancelTemplate();
            }
        }
    }.execute();
    ApplicationManager.getApplication().runReadAction(new Runnable() {

        @Override
        public void run() {
            ASTNode identifier = myDeclaration.getNode().findChildByType(KtTokens.IDENTIFIER);
            if (identifier != null) {
                TextRange range = identifier.getTextRange();
                RangeHighlighter[] highlighters = myEditor.getMarkupModel().getAllHighlighters();
                for (RangeHighlighter highlighter : highlighters) {
                    if (highlighter.getStartOffset() == range.getStartOffset()) {
                        if (highlighter.getEndOffset() == range.getEndOffset()) {
                            highlighter.setGreedyToRight(greedyToRight.get());
                        }
                    }
                }
            }
        }
    });
    if (myEditor.getUserData(INTRODUCE_RESTART) == Boolean.TRUE) {
        myInitialName = myDeclaration.getName();
        performInplaceRefactoring(getSuggestionsForNextRun());
    }
}
Also used : WriteCommandAction(com.intellij.openapi.command.WriteCommandAction) RangeHighlighter(com.intellij.openapi.editor.markup.RangeHighlighter) ASTNode(com.intellij.lang.ASTNode) TemplateState(com.intellij.codeInsight.template.impl.TemplateState) Result(com.intellij.openapi.application.Result)

Example 4 with TemplateState

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

the class ShowIntentionActionsHandler method invoke.

@Override
public void invoke(@NotNull final Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    PsiDocumentManager.getInstance(project).commitAllDocuments();
    if (editor instanceof EditorWindow) {
        editor = ((EditorWindow) editor).getDelegate();
        file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
    }
    final LookupEx lookup = LookupManager.getActiveLookup(editor);
    if (lookup != null) {
        lookup.showElementActions();
        return;
    }
    final DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(project);
    letAutoImportComplete(editor, file, codeAnalyzer);
    ShowIntentionsPass.IntentionsInfo intentions = new ShowIntentionsPass.IntentionsInfo();
    ShowIntentionsPass.getActionsToShow(editor, file, intentions, -1);
    IntentionHintComponent hintComponent = codeAnalyzer.getLastIntentionHint();
    if (hintComponent != null) {
        IntentionHintComponent.PopupUpdateResult result = hintComponent.isForEditor(editor) ? hintComponent.updateActions(intentions) : IntentionHintComponent.PopupUpdateResult.HIDE_AND_RECREATE;
        if (result == IntentionHintComponent.PopupUpdateResult.HIDE_AND_RECREATE) {
            hintComponent.hide();
        }
    }
    if (HintManagerImpl.getInstanceImpl().performCurrentQuestionAction())
        return;
    //intentions check isWritable before modification: if (!file.isWritable()) return;
    TemplateState state = TemplateManagerImpl.getTemplateState(editor);
    if (state != null && !state.isFinished()) {
        return;
    }
    if (!intentions.isEmpty()) {
        IntentionHintComponent.showIntentionHint(project, file, editor, intentions, true);
    }
}
Also used : ShowIntentionsPass(com.intellij.codeInsight.daemon.impl.ShowIntentionsPass) DaemonCodeAnalyzerImpl(com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl) LookupEx(com.intellij.codeInsight.lookup.LookupEx) TemplateState(com.intellij.codeInsight.template.impl.TemplateState) EditorWindow(com.intellij.injected.editor.EditorWindow)

Example 5 with TemplateState

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

the class MyLookupExpression method initLookupItems.

private static LookupElement[] initLookupItems(LinkedHashSet<String> names, PsiNamedElement elementToRename, PsiElement nameSuggestionContext, final boolean shouldSelectAll) {
    if (names == null) {
        names = new LinkedHashSet<>();
        for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) {
            final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(elementToRename, nameSuggestionContext, names);
            if (suggestedNameInfo != null && provider instanceof PreferrableNameSuggestionProvider && !((PreferrableNameSuggestionProvider) provider).shouldCheckOthers()) {
                break;
            }
        }
    }
    final LookupElement[] lookupElements = new LookupElement[names.size()];
    final Iterator<String> iterator = names.iterator();
    for (int i = 0; i < lookupElements.length; i++) {
        final String suggestion = iterator.next();
        lookupElements[i] = LookupElementBuilder.create(suggestion).withInsertHandler(new InsertHandler<LookupElement>() {

            @Override
            public void handleInsert(InsertionContext context, LookupElement item) {
                if (shouldSelectAll)
                    return;
                final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(context.getEditor());
                final TemplateState templateState = TemplateManagerImpl.getTemplateState(topLevelEditor);
                if (templateState != null) {
                    final TextRange range = templateState.getCurrentVariableRange();
                    if (range != null) {
                        topLevelEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), suggestion);
                    }
                }
            }
        });
    }
    return lookupElements;
}
Also used : PreferrableNameSuggestionProvider(com.intellij.refactoring.rename.PreferrableNameSuggestionProvider) NameSuggestionProvider(com.intellij.refactoring.rename.NameSuggestionProvider) TextRange(com.intellij.openapi.util.TextRange) PreferrableNameSuggestionProvider(com.intellij.refactoring.rename.PreferrableNameSuggestionProvider) LookupElement(com.intellij.codeInsight.lookup.LookupElement) InsertionContext(com.intellij.codeInsight.completion.InsertionContext) TemplateState(com.intellij.codeInsight.template.impl.TemplateState) SuggestedNameInfo(com.intellij.psi.codeStyle.SuggestedNameInfo) InsertHandler(com.intellij.codeInsight.completion.InsertHandler) Editor(com.intellij.openapi.editor.Editor)

Aggregations

TemplateState (com.intellij.codeInsight.template.impl.TemplateState)47 TextRange (com.intellij.openapi.util.TextRange)14 Editor (com.intellij.openapi.editor.Editor)11 Project (com.intellij.openapi.project.Project)8 AbstractInplaceIntroducer (com.intellij.refactoring.introduce.inplace.AbstractInplaceIntroducer)6 EditorWindow (com.intellij.injected.editor.EditorWindow)3 Document (com.intellij.openapi.editor.Document)3 SelectionModel (com.intellij.openapi.editor.SelectionModel)3 OpenFileDescriptor (com.intellij.openapi.fileEditor.OpenFileDescriptor)3 VirtualFile (com.intellij.openapi.vfs.VirtualFile)3 RelativePoint (com.intellij.ui.awt.RelativePoint)3 TypeExpression (com.intellij.codeInsight.intention.impl.TypeExpression)2 LookupImpl (com.intellij.codeInsight.lookup.impl.LookupImpl)2 TextResult (com.intellij.codeInsight.template.TextResult)2 Result (com.intellij.openapi.application.Result)2 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)2 CaretModel (com.intellij.openapi.editor.CaretModel)2 LogicalPosition (com.intellij.openapi.editor.LogicalPosition)2 DocumentAdapter (com.intellij.openapi.editor.event.DocumentAdapter)2 DocumentEvent (com.intellij.openapi.editor.event.DocumentEvent)2