Search in sources :

Example 1 with Document

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

the class GroovyEnterHandler method preprocessEnter.

@Override
public Result preprocessEnter(@NotNull PsiFile file, @NotNull Editor editor, @NotNull Ref<Integer> caretOffset, @NotNull Ref<Integer> caretAdvance, @NotNull DataContext dataContext, EditorActionHandler originalHandler) {
    Document document = editor.getDocument();
    Project project = file.getProject();
    CaretModel caretModel = editor.getCaretModel();
    if (!(file instanceof GroovyFileBase)) {
        return Result.Continue;
    }
    int docLength = document.getTextLength();
    if (docLength == 0) {
        return Result.Continue;
    }
    final int caret = caretModel.getOffset();
    final EditorHighlighter highlighter = ((EditorEx) editor).getHighlighter();
    if (caret >= 1 && caret < docLength && CodeInsightSettings.getInstance().SMART_INDENT_ON_ENTER) {
        HighlighterIterator iterator = highlighter.createIterator(caret);
        iterator.retreat();
        while (!iterator.atEnd() && TokenType.WHITE_SPACE == iterator.getTokenType()) {
            iterator.retreat();
        }
        boolean afterArrow = !iterator.atEnd() && iterator.getTokenType() == GroovyTokenTypes.mCLOSABLE_BLOCK_OP;
        if (afterArrow) {
            originalHandler.execute(editor, dataContext);
            PsiDocumentManager.getInstance(project).commitDocument(document);
            CodeStyleManager.getInstance(project).adjustLineIndent(file, caretModel.getOffset());
        }
        iterator = highlighter.createIterator(caretModel.getOffset());
        while (!iterator.atEnd() && TokenType.WHITE_SPACE == iterator.getTokenType()) {
            iterator.advance();
        }
        if (!iterator.atEnd() && GroovyTokenTypes.mRCURLY == iterator.getTokenType()) {
            PsiDocumentManager.getInstance(project).commitDocument(document);
            final PsiElement element = file.findElementAt(iterator.getStart());
            if (element != null && element.getNode().getElementType() == GroovyTokenTypes.mRCURLY && element.getParent() instanceof GrClosableBlock && docLength > caret && afterArrow) {
                return Result.DefaultForceIndent;
            }
        }
        if (afterArrow) {
            return Result.Stop;
        }
        if (editor.isInsertMode() && !HandlerUtils.isReadOnly(editor) && !editor.getSelectionModel().hasSelection() && handleFlyingGeese(editor, caret, dataContext, originalHandler, file)) {
            return Result.DefaultForceIndent;
        }
    }
    if (handleEnter(editor, dataContext, project, originalHandler))
        return Result.Stop;
    return Result.Continue;
}
Also used : Project(com.intellij.openapi.project.Project) GroovyFileBase(org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase) CaretModel(com.intellij.openapi.editor.CaretModel) EditorEx(com.intellij.openapi.editor.ex.EditorEx) GrClosableBlock(org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock) Document(com.intellij.openapi.editor.Document) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator) EditorHighlighter(com.intellij.openapi.editor.highlighter.EditorHighlighter)

Example 2 with Document

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

the class GroovyEnterHandler method handleInString.

private static boolean handleInString(Editor editor, int caretOffset, DataContext dataContext, EditorActionHandler originalHandler) {
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null)
        return false;
    final VirtualFile vfile = FileDocumentManager.getInstance().getFile(editor.getDocument());
    assert vfile != null;
    PsiFile file = PsiManager.getInstance(project).findFile(vfile);
    Document document = editor.getDocument();
    String fileText = document.getText();
    if (fileText.length() == caretOffset)
        return false;
    if (!checkStringApplicable(editor, caretOffset))
        return false;
    if (file == null)
        return false;
    PsiDocumentManager.getInstance(project).commitDocument(document);
    final PsiElement stringElement = inferStringPair(file, caretOffset);
    if (stringElement == null)
        return false;
    ASTNode node = stringElement.getNode();
    final IElementType nodeElementType = node.getElementType();
    boolean isInsertIndent = isInsertIndent(caretOffset, stringElement.getTextRange().getStartOffset(), fileText);
    // For simple String literals like 'abc'
    CaretModel caretModel = editor.getCaretModel();
    if (nodeElementType == GroovyTokenTypes.mSTRING_LITERAL) {
        if (isSingleQuoteString(stringElement)) {
            //the case of print '\<caret>'
            if (isSlashBeforeCaret(caretOffset, fileText)) {
                EditorModificationUtil.insertStringAtCaret(editor, "\n");
            } else if (stringElement.getParent() instanceof GrReferenceExpression) {
                TextRange range = stringElement.getTextRange();
                convertEndToMultiline(range.getEndOffset(), document, fileText, '\'');
                document.insertString(range.getStartOffset(), "''");
                caretModel.moveToOffset(caretOffset + 2);
                EditorModificationUtil.insertStringAtCaret(editor, "\n");
            } else {
                EditorModificationUtil.insertStringAtCaret(editor, "'+");
                originalHandler.execute(editor, dataContext);
                EditorModificationUtil.insertStringAtCaret(editor, "'");
                PsiDocumentManager.getInstance(project).commitDocument(document);
                CodeStyleManager.getInstance(project).reformatRange(file, caretOffset, caretModel.getOffset());
            }
        } else {
            insertLineFeedInString(editor, dataContext, originalHandler, isInsertIndent);
        }
        return true;
    }
    if (GSTRING_TOKENS.contains(nodeElementType) || nodeElementType == GroovyElementTypes.GSTRING_CONTENT && GSTRING_TOKENS.contains(node.getFirstChildNode().getElementType()) || nodeElementType == GroovyTokenTypes.mDOLLAR && node.getTreeParent().getTreeParent().getElementType() == GroovyElementTypes.GSTRING) {
        PsiElement parent = stringElement.getParent();
        if (nodeElementType == GroovyTokenTypes.mGSTRING_LITERAL) {
            parent = stringElement;
        } else {
            while (parent != null && !(parent instanceof GrLiteral)) {
                parent = parent.getParent();
            }
        }
        if (parent == null)
            return false;
        if (isDoubleQuotedString(parent)) {
            PsiElement exprSibling = stringElement.getNextSibling();
            boolean rightFromDollar = exprSibling instanceof GrExpression && exprSibling.getTextRange().getStartOffset() == caretOffset;
            if (rightFromDollar)
                caretOffset--;
            TextRange parentRange = parent.getTextRange();
            if (rightFromDollar || parent.getParent() instanceof GrReferenceExpression) {
                convertEndToMultiline(parent.getTextRange().getEndOffset(), document, fileText, '"');
                document.insertString(parentRange.getStartOffset(), "\"\"");
                caretModel.moveToOffset(caretOffset + 2);
                EditorModificationUtil.insertStringAtCaret(editor, "\n");
                if (rightFromDollar) {
                    caretModel.moveCaretRelatively(1, 0, false, false, true);
                }
            } else if (isSlashBeforeCaret(caretOffset, fileText)) {
                EditorModificationUtil.insertStringAtCaret(editor, "\n");
            } else {
                EditorModificationUtil.insertStringAtCaret(editor, "\"+");
                originalHandler.execute(editor, dataContext);
                EditorModificationUtil.insertStringAtCaret(editor, "\"");
                PsiDocumentManager.getInstance(project).commitDocument(document);
                CodeStyleManager.getInstance(project).reformatRange(file, caretOffset, caretModel.getOffset());
            }
        } else {
            insertLineFeedInString(editor, dataContext, originalHandler, isInsertIndent);
        }
        return true;
    }
    if (REGEX_TOKENS.contains(nodeElementType) || nodeElementType == GroovyElementTypes.GSTRING_CONTENT && REGEX_TOKENS.contains(node.getFirstChildNode().getElementType()) || nodeElementType == GroovyTokenTypes.mDOLLAR && node.getTreeParent().getTreeParent().getElementType() == GroovyElementTypes.REGEX) {
        PsiElement parent = stringElement.getParent();
        if (nodeElementType == GroovyTokenTypes.mREGEX_LITERAL || nodeElementType == GroovyTokenTypes.mDOLLAR_SLASH_REGEX_LITERAL) {
            parent = stringElement;
        } else {
            while (parent != null && !(parent instanceof GrLiteral)) {
                parent = parent.getParent();
            }
        }
        if (parent == null || parent.getLastChild() instanceof PsiErrorElement)
            return false;
        PsiElement exprSibling = stringElement.getNextSibling();
        boolean rightFromDollar = exprSibling instanceof GrExpression && exprSibling.getTextRange().getStartOffset() == caretOffset;
        if (rightFromDollar) {
            caretModel.moveToOffset(caretOffset - 1);
        }
        insertLineFeedInString(editor, dataContext, originalHandler, isInsertIndent);
        if (rightFromDollar) {
            caretModel.moveCaretRelatively(1, 0, false, false, true);
        }
        return true;
    }
    return false;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) CaretModel(com.intellij.openapi.editor.CaretModel) TextRange(com.intellij.openapi.util.TextRange) GrExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression) Document(com.intellij.openapi.editor.Document) GrReferenceExpression(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression) IElementType(com.intellij.psi.tree.IElementType) Project(com.intellij.openapi.project.Project) ASTNode(com.intellij.lang.ASTNode) GrLiteral(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral)

Example 3 with Document

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

the class GroovyStatementMover method checkAvailable.

@Override
public boolean checkAvailable(@NotNull Editor editor, @NotNull PsiFile file, @NotNull MoveInfo info, boolean down) {
    final Project project = file.getProject();
    if (!HandlerUtils.canBeInvoked(editor, project) || !(file instanceof GroovyFileBase))
        return false;
    LineRange range = getLineRangeFromSelection(editor);
    final Document document = editor.getDocument();
    final int offset = document.getLineStartOffset(range.startLine);
    final GrLiteral literal = PsiTreeUtil.findElementOfClassAtOffset(file, offset, GrLiteral.class, false);
    //multiline string
    if (literal != null && literal.textContains('\n'))
        return false;
    final GroovyPsiElement pivot = getElementToMove((GroovyFileBase) file, offset);
    if (pivot == null)
        return false;
    final LineRange pivotRange = getLineRange(pivot);
    range = new LineRange(Math.min(range.startLine, pivotRange.startLine), Math.max(range.endLine, pivotRange.endLine));
    final GroovyPsiElement scope = PsiTreeUtil.getParentOfType(pivot, GrMethod.class, GrTypeDefinitionBody.class, GroovyFileBase.class);
    final boolean stmtLevel = isStatement(pivot);
    boolean topLevel = pivot instanceof GrTypeDefinition && pivot.getParent() instanceof GroovyFileBase;
    final List<LineRange> allRanges = allRanges(scope, stmtLevel, topLevel);
    LineRange prev = null;
    LineRange next = null;
    for (LineRange each : allRanges) {
        if (each.endLine <= range.startLine) {
            prev = each;
        }
        if (each.containsLine(range.startLine)) {
            range = new LineRange(each.startLine, range.endLine);
        }
        if (each.startLine < range.endLine && each.endLine > range.endLine) {
            range = new LineRange(range.startLine, each.endLine);
        }
        if (each.startLine >= range.endLine && next == null) {
            next = each;
        }
    }
    info.toMove = range;
    info.toMove2 = down ? next : prev;
    return true;
}
Also used : Project(com.intellij.openapi.project.Project) GroovyFileBase(org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase) GroovyPsiElement(org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement) GrTypeDefinition(org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition) Document(com.intellij.openapi.editor.Document) LineRange(com.intellij.codeInsight.editorActions.moveUpDown.LineRange) GrLiteral(org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral)

Example 4 with Document

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

the class DynamicDialog method setUpTypeComboBox.

private void setUpTypeComboBox(TypeConstraint[] typeConstraints) {
    final EditorComboBoxEditor comboEditor = new EditorComboBoxEditor(myProject, GroovyFileType.GROOVY_FILE_TYPE);
    final Document document = createDocument("");
    LOG.assertTrue(document != null);
    comboEditor.setItem(document);
    myTypeComboBox.setEditor(comboEditor);
    myTypeComboBox.setEditable(true);
    myTypeComboBox.grabFocus();
    PsiType type = typeConstraints.length == 1 ? typeConstraints[0].getDefaultType() : TypesUtil.getJavaLangObject(myContext);
    myTypeComboBox.getEditor().setItem(createDocument(type.getCanonicalText()));
}
Also used : EditorComboBoxEditor(com.intellij.ui.EditorComboBoxEditor) Document(com.intellij.openapi.editor.Document)

Example 5 with Document

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

the class DynamicDialog method doOKAction.

@Override
protected void doOKAction() {
    super.doOKAction();
    mySettings.setContainingClassName((String) myClassComboBox.getSelectedItem());
    mySettings.setStatic(myStaticCheckBox.isSelected());
    GrTypeElement typeElement = getEnteredTypeName();
    if (typeElement == null) {
        mySettings.setType(CommonClassNames.JAVA_LANG_OBJECT);
    } else {
        PsiType type = typeElement.getType();
        if (type instanceof PsiPrimitiveType) {
            type = TypesUtil.boxPrimitiveType(type, typeElement.getManager(), ProjectScope.getAllScope(myProject));
        }
        final String typeQualifiedName = type.getCanonicalText();
        if (typeQualifiedName != null) {
            mySettings.setType(typeQualifiedName);
        } else {
            mySettings.setType(type.getPresentableText());
        }
    }
    final Document document = PsiDocumentManager.getInstance(myProject).getDocument(myContext.getContainingFile());
    CommandProcessor.getInstance().executeCommand(myProject, () -> {
        UndoManager.getInstance(myProject).undoableActionPerformed(new GlobalUndoableAction(document) {

            @Override
            public void undo() throws UnexpectedUndoException {
                final DItemElement itemElement;
                if (mySettings.isMethod()) {
                    final List<ParamInfo> myPairList = mySettings.getParams();
                    final String[] argumentsTypes = QuickfixUtil.getArgumentsTypes(myPairList);
                    itemElement = myDynamicManager.findConcreteDynamicMethod(mySettings.getContainingClassName(), mySettings.getName(), argumentsTypes);
                } else {
                    itemElement = myDynamicManager.findConcreteDynamicProperty(mySettings.getContainingClassName(), mySettings.getName());
                }
                if (itemElement == null) {
                    Messages.showWarningDialog(myProject, GroovyInspectionBundle.message("Cannot.perform.undo.operation"), GroovyInspectionBundle.message("Undo.disable"));
                    return;
                }
                final DClassElement classElement = myDynamicManager.getClassElementByItem(itemElement);
                if (classElement == null) {
                    Messages.showWarningDialog(myProject, GroovyInspectionBundle.message("Cannot.perform.undo.operation"), GroovyInspectionBundle.message("Undo.disable"));
                    return;
                }
                removeElement(itemElement);
                if (classElement.getMethods().isEmpty() && classElement.getProperties().isEmpty()) {
                    myDynamicManager.removeClassElement(classElement);
                }
            }

            @Override
            public void redo() throws UnexpectedUndoException {
                addElement(mySettings);
            }
        });
        addElement(mySettings);
    }, "Add dynamic element", null);
}
Also used : GrTypeElement(org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement) DClassElement(org.jetbrains.plugins.groovy.annotator.intentions.dynamic.elements.DClassElement) UnexpectedUndoException(com.intellij.openapi.command.undo.UnexpectedUndoException) GlobalUndoableAction(com.intellij.openapi.command.undo.GlobalUndoableAction) List(java.util.List) Document(com.intellij.openapi.editor.Document) DItemElement(org.jetbrains.plugins.groovy.annotator.intentions.dynamic.elements.DItemElement)

Aggregations

Document (com.intellij.openapi.editor.Document)1165 VirtualFile (com.intellij.openapi.vfs.VirtualFile)265 PsiFile (com.intellij.psi.PsiFile)207 Project (com.intellij.openapi.project.Project)178 NotNull (org.jetbrains.annotations.NotNull)151 Nullable (org.jetbrains.annotations.Nullable)137 TextRange (com.intellij.openapi.util.TextRange)131 PsiDocumentManager (com.intellij.psi.PsiDocumentManager)126 PsiElement (com.intellij.psi.PsiElement)126 Editor (com.intellij.openapi.editor.Editor)112 LightVirtualFile (com.intellij.testFramework.LightVirtualFile)60 FileDocumentManager (com.intellij.openapi.fileEditor.FileDocumentManager)48 IncorrectOperationException (com.intellij.util.IncorrectOperationException)44 IOException (java.io.IOException)44 RangeMarker (com.intellij.openapi.editor.RangeMarker)37 ArrayList (java.util.ArrayList)35 MockVirtualFile (com.intellij.mock.MockVirtualFile)33 File (java.io.File)33 List (java.util.List)33 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)30