Search in sources :

Example 36 with CaretModel

use of com.intellij.openapi.editor.CaretModel in project intellij-community by JetBrains.

the class SelectionQuotingTypedHandler method beforeSelectionRemoved.

@Override
public Result beforeSelectionRemoved(char c, Project project, Editor editor, PsiFile file) {
    SelectionModel selectionModel = editor.getSelectionModel();
    if (CodeInsightSettings.getInstance().SURROUND_SELECTION_ON_QUOTE_TYPED && selectionModel.hasSelection() && isDelimiter(c)) {
        String selectedText = selectionModel.getSelectedText();
        if (!StringUtil.isEmpty(selectedText)) {
            final int selectionStart = selectionModel.getSelectionStart();
            final int selectionEnd = selectionModel.getSelectionEnd();
            if (selectedText.length() > 1) {
                final char firstChar = selectedText.charAt(0);
                final char lastChar = selectedText.charAt(selectedText.length() - 1);
                if (isSimilarDelimiters(firstChar, c) && lastChar == getMatchingDelimiter(firstChar) && (isQuote(firstChar) || firstChar != c) && !shouldSkipReplacementOfQuotesOrBraces(file, editor, selectedText, c) && selectedText.indexOf(lastChar, 1) == selectedText.length() - 1) {
                    selectedText = selectedText.substring(1, selectedText.length() - 1);
                }
            }
            final int caretOffset = selectionModel.getSelectionStart();
            final char c2 = getMatchingDelimiter(c);
            final String newText = String.valueOf(c) + selectedText + c2;
            boolean ltrSelection = selectionModel.getLeadSelectionOffset() != selectionModel.getSelectionEnd();
            boolean restoreStickySelection = editor instanceof EditorEx && ((EditorEx) editor).isStickySelection();
            selectionModel.removeSelection();
            editor.getDocument().replaceString(selectionStart, selectionEnd, newText);
            TextRange replacedTextRange = Registry.is("editor.smarterSelectionQuoting") ? new TextRange(caretOffset + 1, caretOffset + newText.length() - 1) : new TextRange(caretOffset, caretOffset + newText.length());
            // selection is removed here
            if (replacedTextRange.getEndOffset() <= editor.getDocument().getTextLength()) {
                if (restoreStickySelection) {
                    EditorEx editorEx = (EditorEx) editor;
                    CaretModel caretModel = editorEx.getCaretModel();
                    caretModel.moveToOffset(ltrSelection ? replacedTextRange.getStartOffset() : replacedTextRange.getEndOffset());
                    editorEx.setStickySelection(true);
                    caretModel.moveToOffset(ltrSelection ? replacedTextRange.getEndOffset() : replacedTextRange.getStartOffset());
                } else {
                    if (ltrSelection || editor instanceof EditorWindow) {
                        editor.getSelectionModel().setSelection(replacedTextRange.getStartOffset(), replacedTextRange.getEndOffset());
                    } else {
                        editor.getSelectionModel().setSelection(replacedTextRange.getEndOffset(), replacedTextRange.getStartOffset());
                    }
                    if (Registry.is("editor.smarterSelectionQuoting")) {
                        editor.getCaretModel().moveToOffset(ltrSelection ? replacedTextRange.getEndOffset() : replacedTextRange.getStartOffset());
                    }
                }
            }
            return Result.STOP;
        }
    }
    return super.beforeSelectionRemoved(c, project, editor, file);
}
Also used : EditorEx(com.intellij.openapi.editor.ex.EditorEx) CaretModel(com.intellij.openapi.editor.CaretModel) SelectionModel(com.intellij.openapi.editor.SelectionModel) TextRange(com.intellij.openapi.util.TextRange) EditorWindow(com.intellij.injected.editor.EditorWindow)

Example 37 with CaretModel

use of com.intellij.openapi.editor.CaretModel in project intellij-community by JetBrains.

the class ChangeSignatureGestureTest method testAddParamChangeReturnType.

public void testAddParamChangeReturnType() {
    doTest(() -> {
        myFixture.type("int param");
        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
        CaretModel model = myFixture.getEditor().getCaretModel();
        PsiElement element = myFixture.getElementAtCaret();
        PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
        assertTrue(method != null);
        PsiTypeElement returnTypeElement = method.getReturnTypeElement();
        assertTrue(returnTypeElement != null);
        model.moveToOffset(returnTypeElement.getTextRange().getEndOffset());
        int i = returnTypeElement.getTextLength();
        while (i-- > 0) {
            myFixture.type('\b');
        }
        myFixture.type("boolean");
    });
}
Also used : CaretModel(com.intellij.openapi.editor.CaretModel) PsiMethod(com.intellij.psi.PsiMethod) PsiTypeElement(com.intellij.psi.PsiTypeElement) PsiElement(com.intellij.psi.PsiElement)

Example 38 with CaretModel

use of com.intellij.openapi.editor.CaretModel in project intellij-community by JetBrains.

the class MavenPomXmlCompletionTagListenerContributor method fillCompletionVariants.

@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull final CompletionResultSet result) {
    if (TemplateManager.getInstance(parameters.getOriginalFile().getProject()).getActiveTemplate(parameters.getEditor()) != null) {
        // Don't brake the template.
        return;
    }
    PsiFile psiFile = parameters.getOriginalFile();
    if (!(psiFile instanceof XmlFile))
        return;
    if (!MavenDomUtil.isProjectFile(psiFile))
        return;
    DomFileDescription<?> description = DomManager.getDomManager(psiFile.getProject()).getDomFileDescription((XmlFile) psiFile);
    if (!(description instanceof MavenDomProjectModelDescription))
        return;
    result.runRemainingContributors(parameters, r -> {
        final LookupElement lookupElement = r.getLookupElement();
        if (myHandledTags.contains(lookupElement.getLookupString())) {
            LookupElement decorator = LookupElementDecorator.withInsertHandler(lookupElement, new InsertHandler<LookupElementDecorator<LookupElement>>() {

                @Override
                public void handleInsert(final InsertionContext context, LookupElementDecorator<LookupElement> item) {
                    lookupElement.handleInsert(context);
                    Object object = lookupElement.getObject();
                    if ("dependency".equals(lookupElement.getLookupString()) && object instanceof XmlTag && "maven-4.0.0.xsd".equals(((XmlTag) object).getContainingFile().getName())) {
                        context.commitDocument();
                        CaretModel caretModel = context.getEditor().getCaretModel();
                        PsiElement psiElement = context.getFile().findElementAt(caretModel.getOffset());
                        XmlTag xmlTag = PsiTreeUtil.getParentOfType(psiElement, XmlTag.class);
                        if (xmlTag != null) {
                            DomElement domElement = DomManager.getDomManager(context.getProject()).getDomElement(xmlTag);
                            if (domElement instanceof MavenDomDependency) {
                                String s = "\n<groupId></groupId>\n<artifactId></artifactId>\n";
                                context.getDocument().insertString(caretModel.getOffset(), s);
                                caretModel.moveToOffset(caretModel.getOffset() + s.length() - "</artifactId>\n".length());
                                context.commitDocument();
                                new ReformatCodeProcessor(context.getProject(), context.getFile(), xmlTag.getTextRange(), false).run();
                                MavenDependencyCompletionUtil.invokeCompletion(context, CompletionType.BASIC);
                            }
                        }
                    }
                }
            });
            r = r.withLookupElement(decorator);
        }
        result.passResult(r);
    });
}
Also used : CaretModel(com.intellij.openapi.editor.CaretModel) XmlFile(com.intellij.psi.xml.XmlFile) LookupElementDecorator(com.intellij.codeInsight.lookup.LookupElementDecorator) ReformatCodeProcessor(com.intellij.codeInsight.actions.ReformatCodeProcessor) LookupElement(com.intellij.codeInsight.lookup.LookupElement) MavenDomDependency(org.jetbrains.idea.maven.dom.model.MavenDomDependency) DomElement(com.intellij.util.xml.DomElement) MavenDomProjectModelDescription(org.jetbrains.idea.maven.dom.MavenDomProjectModelDescription) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement) XmlTag(com.intellij.psi.xml.XmlTag)

Example 39 with CaretModel

use of com.intellij.openapi.editor.CaretModel in project intellij-community by JetBrains.

the class YAMLBreadcrumbsTest method testAll.

public void testAll() {
    myFixture.configureByText(YAMLFileType.YML, INPUT);
    final CaretModel caretModel = myFixture.getEditor().getCaretModel();
    final String result = caretModel.getAllCarets().stream().map(Caret::getOffset).collect(Collectors.toList()).stream().map((offset) -> {
        caretModel.moveToOffset(offset);
        return getBreadcrumbs(myFixture).stream().map(BreadcrumbsItem::toString).reduce((left, right) -> right + left).orElse("[]");
    }).reduce((left, right) -> left + "\n------\n" + right).orElse("");
    assertSameLines(OUTPUT, result);
}
Also used : Language(com.intellij.lang.Language) Extensions(com.intellij.openapi.extensions.Extensions) BreadcrumbsItem(com.intellij.xml.breadcrumbs.BreadcrumbsItem) Arrays(java.util.Arrays) CodeInsightTestFixture(com.intellij.testFramework.fixtures.CodeInsightTestFixture) ContainerUtil(com.intellij.util.containers.ContainerUtil) CaretModel(com.intellij.openapi.editor.CaretModel) Collectors(java.util.stream.Collectors) Caret(com.intellij.openapi.editor.Caret) ArrayList(java.util.ArrayList) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) YAMLFileType(org.jetbrains.yaml.YAMLFileType) LightPlatformCodeInsightFixtureTestCase(com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase) PsiElement(com.intellij.psi.PsiElement) BreadcrumbsInfoProvider(com.intellij.xml.breadcrumbs.BreadcrumbsInfoProvider) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) CaretModel(com.intellij.openapi.editor.CaretModel) BreadcrumbsItem(com.intellij.xml.breadcrumbs.BreadcrumbsItem)

Example 40 with CaretModel

use of com.intellij.openapi.editor.CaretModel in project intellij-community by JetBrains.

the class JavaMethodCallElement method showParameterHints.

public static void showParameterHints(InsertionContext context, PsiMethod method, PsiCallExpression methodCall) {
    PsiParameterList parameterList = method.getParameterList();
    int parametersCount = parameterList.getParametersCount();
    if (methodCall == null || parametersCount == 0 || context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR || Registry.is("java.completion.argument.live.template") || !Registry.is("java.completion.argument.hints")) {
        return;
    }
    Editor editor = context.getEditor();
    CaretModel caretModel = editor.getCaretModel();
    int offset = caretModel.getOffset();
    // avoid caret impact on hints location
    caretModel.moveToOffset(offset - 1);
    editor.getDocument().insertString(offset, StringUtil.repeat(", ", parametersCount - 1));
    List<Inlay> addedHints = new ArrayList<>(parametersCount);
    for (PsiParameter parameter : parameterList.getParameters()) {
        String name = parameter.getName();
        if (name != null) {
            addedHints.add(ParameterHintsPresentationManager.getInstance().addHint(editor, offset, name + ":", false, true));
        }
        offset += 2;
    }
    int braceOffset = caretModel.getOffset();
    caretModel.moveToLogicalPosition(editor.offsetToLogicalPosition(braceOffset + 1).leanForward(true));
    Project project = context.getProject();
    MethodParameterInfoHandler handler = new MethodParameterInfoHandler();
    ShowParameterInfoContext infoContext = new ShowParameterInfoContext(editor, project, context.getFile(), braceOffset, braceOffset);
    handler.findElementForParameterInfo(infoContext);
    Disposer.register(new ParameterInfoController(project, editor, braceOffset, infoContext.getItemsToShow(), null, methodCall.getArgumentList(), handler, false, false), () -> {
        for (Inlay inlay : addedHints) {
            if (inlay != null)
                ParameterHintsPresentationManager.getInstance().unpin(inlay);
        }
    });
}
Also used : CaretModel(com.intellij.openapi.editor.CaretModel) Inlay(com.intellij.openapi.editor.Inlay) ArrayList(java.util.ArrayList) ParameterInfoController(com.intellij.codeInsight.hint.ParameterInfoController) Project(com.intellij.openapi.project.Project) MethodParameterInfoHandler(com.intellij.codeInsight.hint.api.impls.MethodParameterInfoHandler) Editor(com.intellij.openapi.editor.Editor) ShowParameterInfoContext(com.intellij.codeInsight.hint.ShowParameterInfoContext)

Aggregations

CaretModel (com.intellij.openapi.editor.CaretModel)57 Document (com.intellij.openapi.editor.Document)23 PsiElement (com.intellij.psi.PsiElement)14 SelectionModel (com.intellij.openapi.editor.SelectionModel)10 TextRange (com.intellij.openapi.util.TextRange)9 Editor (com.intellij.openapi.editor.Editor)8 Project (com.intellij.openapi.project.Project)7 LogicalPosition (com.intellij.openapi.editor.LogicalPosition)6 Nullable (org.jetbrains.annotations.Nullable)6 EditorEx (com.intellij.openapi.editor.ex.EditorEx)5 IElementType (com.intellij.psi.tree.IElementType)5 LookupElement (com.intellij.codeInsight.lookup.LookupElement)3 EditorHighlighter (com.intellij.openapi.editor.highlighter.EditorHighlighter)3 HighlighterIterator (com.intellij.openapi.editor.highlighter.HighlighterIterator)3 PsiFile (com.intellij.psi.PsiFile)3 List (java.util.List)3 InsertionContext (com.intellij.codeInsight.completion.InsertionContext)2 TemplateState (com.intellij.codeInsight.template.impl.TemplateState)2 Caret (com.intellij.openapi.editor.Caret)2 ScrollingModel (com.intellij.openapi.editor.ScrollingModel)2