Example usage for com.intellij.openapi.editor EditorModificationUtil insertStringAtCaret

List of usage examples for com.intellij.openapi.editor EditorModificationUtil insertStringAtCaret

Introduction

In this page you can find the example usage for com.intellij.openapi.editor EditorModificationUtil insertStringAtCaret.

Prototype

public static int insertStringAtCaret(Editor editor, @NotNull String s, boolean toProcessOverwriteMode,
            int caretShift) 

Source Link

Usage

From source file:com.google.bamboo.soy.insight.typedhandlers.EnterHandler.java

License:Apache License

private static void insertText(PsiFile file, Editor editor, String text, int numChar) {
    EditorModificationUtil.insertStringAtCaret(editor, text, false, numChar);
    PsiDocumentManager.getInstance(file.getProject()).commitDocument(editor.getDocument());
}

From source file:com.intellij.codeInsight.editorActions.JavaTypedHandler.java

License:Apache License

@Override
public Result beforeCharTyped(final char c, final Project project, final Editor editor, final PsiFile file,
        final FileType fileType) {
    if (c == '@' && file instanceof PsiJavaFile) {
        autoPopupJavadocLookup(project, editor);
    } else if (c == '#' || c == '.') {
        autoPopupMemberLookup(project, editor);
    }//w  ww . j ava2s .  c  om

    final FileType originalFileType = getOriginalFileType(file);

    int offsetBefore = editor.getCaretModel().getOffset();

    //important to calculate before inserting charTyped
    myJavaLTTyped = '<' == c && file instanceof PsiJavaFile &&
    // !(file instanceof JspFile) &&
            CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET && PsiUtil.isLanguageLevel5OrHigher(file)
            && isAfterClassLikeIdentifierOrDot(offsetBefore, editor);

    if ('>' == c) {
        if (file instanceof PsiJavaFile
                /* && !(file instanceof JspFile)*/ && CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET
                && PsiUtil.isLanguageLevel5OrHigher(file)) {
            if (handleJavaGT(editor, JavaTokenType.LT, JavaTokenType.GT, INVALID_INSIDE_REFERENCE))
                return Result.STOP;
        }
    }

    if (c == ';') {
        if (handleSemicolon(editor, fileType))
            return Result.STOP;
    }
    if (originalFileType == JavaFileType.INSTANCE && c == '{') {
        int offset = editor.getCaretModel().getOffset();
        if (offset == 0) {
            return Result.CONTINUE;
        }

        HighlighterIterator iterator = ((EditorEx) editor).getHighlighter().createIterator(offset - 1);
        while (!iterator.atEnd() && iterator.getTokenType() == TokenType.WHITE_SPACE) {
            iterator.retreat();
        }
        if (iterator.atEnd() || iterator.getTokenType() == JavaTokenType.RBRACKET
                || iterator.getTokenType() == JavaTokenType.EQ) {
            return Result.CONTINUE;
        }
        PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
        final PsiElement leaf = file.findElementAt(offset);
        if (PsiTreeUtil.getParentOfType(leaf, PsiArrayInitializerExpression.class, false, PsiCodeBlock.class,
                PsiMember.class) != null) {
            return Result.CONTINUE;
        }
        if (PsiTreeUtil.getParentOfType(leaf, PsiCodeBlock.class, false, PsiMember.class) != null) {
            EditorModificationUtil.insertStringAtCaret(editor, "{", false, true);
            TypedHandler.indentOpenedBrace(project, editor);
            return Result.STOP;
        }
    }

    return Result.CONTINUE;
}

From source file:com.intellij.codeInsight.editorActions.PasteHandler.java

License:Apache License

private static void doPaste(final Editor editor, final Project project, final PsiFile file,
        final Document document, final Producer<Transferable> producer) {
    Transferable content = null;/*from w  ww.j  ava2 s.  co  m*/

    if (producer != null) {
        content = producer.produce();
    } else {
        CopyPasteManager manager = CopyPasteManager.getInstance();
        if (manager.areDataFlavorsAvailable(DataFlavor.stringFlavor)) {
            content = manager.getContents();
            if (content != null) {
                manager.stopKillRings();
            }
        }
    }

    if (content != null) {
        String text = null;
        try {
            text = (String) content.getTransferData(DataFlavor.stringFlavor);
        } catch (Exception e) {
            editor.getComponent().getToolkit().beep();
        }
        if (text == null)
            return;

        final CodeInsightSettings settings = CodeInsightSettings.getInstance();

        final Map<CopyPastePostProcessor, List<? extends TextBlockTransferableData>> extraData = new HashMap<CopyPastePostProcessor, List<? extends TextBlockTransferableData>>();
        Collection<TextBlockTransferableData> allValues = new ArrayList<TextBlockTransferableData>();
        for (CopyPastePostProcessor<? extends TextBlockTransferableData> processor : Extensions
                .getExtensions(CopyPastePostProcessor.EP_NAME)) {
            List<? extends TextBlockTransferableData> data = processor.extractTransferableData(content);
            if (!data.isEmpty()) {
                extraData.put(processor, data);
                allValues.addAll(data);
            }
        }

        text = TextBlockTransferable.convertLineSeparators(text, "\n", allValues);

        final CaretModel caretModel = editor.getCaretModel();
        final SelectionModel selectionModel = editor.getSelectionModel();
        final int col = caretModel.getLogicalPosition().column;

        // There is a possible case that we want to perform paste while there is an active selection at the editor and caret is located
        // inside it (e.g. Ctrl+A is pressed while caret is not at the zero column). We want to insert the text at selection start column
        // then, hence, inserted block of text should be indented according to the selection start as well.
        final int blockIndentAnchorColumn;
        final int caretOffset = caretModel.getOffset();
        if (selectionModel.hasSelection() && caretOffset >= selectionModel.getSelectionStart()) {
            blockIndentAnchorColumn = editor.offsetToLogicalPosition(selectionModel.getSelectionStart()).column;
        } else {
            blockIndentAnchorColumn = col;
        }

        // We assume that EditorModificationUtil.insertStringAtCaret() is smart enough to remove currently selected text (if any).

        RawText rawText = RawText.fromTransferable(content);
        String newText = text;
        for (CopyPastePreProcessor preProcessor : Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
            newText = preProcessor.preprocessOnPaste(project, file, editor, newText, rawText);
        }
        int indentOptions = text.equals(newText) ? settings.REFORMAT_ON_PASTE
                : CodeInsightSettings.REFORMAT_BLOCK;
        text = newText;

        if (LanguageFormatting.INSTANCE.forContext(file) == null
                && indentOptions != CodeInsightSettings.NO_REFORMAT) {
            indentOptions = CodeInsightSettings.INDENT_BLOCK;
        }

        final String _text = text;
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
            @Override
            public void run() {
                EditorModificationUtil.insertStringAtCaret(editor, _text, false, true);
            }
        });

        int length = text.length();
        int offset = caretModel.getOffset() - length;
        if (offset < 0) {
            length += offset;
            offset = 0;
        }
        final RangeMarker bounds = document.createRangeMarker(offset, offset + length);

        caretModel.moveToOffset(bounds.getEndOffset());
        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
        selectionModel.removeSelection();

        final Ref<Boolean> indented = new Ref<Boolean>(Boolean.FALSE);
        for (Map.Entry<CopyPastePostProcessor, List<? extends TextBlockTransferableData>> e : extraData
                .entrySet()) {
            //noinspection unchecked
            e.getKey().processTransferableData(project, editor, bounds, caretOffset, indented, e.getValue());
        }

        boolean pastedTextContainsWhiteSpacesOnly = CharArrayUtil.shiftForward(document.getCharsSequence(),
                bounds.getStartOffset(), " \n\t") >= bounds.getEndOffset();

        VirtualFile virtualFile = file.getVirtualFile();
        if (!pastedTextContainsWhiteSpacesOnly && (virtualFile == null
                || !SingleRootFileViewProvider.isTooLargeForIntelligence(virtualFile))) {
            final int indentOptions1 = indentOptions;

            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                @Override
                public void run() {
                    PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
                    switch (indentOptions1) {
                    case CodeInsightSettings.INDENT_BLOCK:
                        if (!indented.get()) {
                            indentBlock(project, editor, bounds.getStartOffset(), bounds.getEndOffset(),
                                    blockIndentAnchorColumn);
                        }
                        break;

                    case CodeInsightSettings.INDENT_EACH_LINE:
                        if (!indented.get()) {
                            indentEachLine(project, editor, bounds.getStartOffset(), bounds.getEndOffset());
                        }
                        break;

                    case CodeInsightSettings.REFORMAT_BLOCK:
                        indentEachLine(project, editor, bounds.getStartOffset(), bounds.getEndOffset()); // this is needed for example when inserting a comment before method
                        reformatBlock(project, editor, bounds.getStartOffset(), bounds.getEndOffset());
                        break;
                    }
                }
            });
        }

        if (bounds.isValid()) {
            caretModel.moveToOffset(bounds.getEndOffset());
            editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
            selectionModel.removeSelection();
            editor.putUserData(EditorEx.LAST_PASTED_REGION, TextRange.create(bounds));
        }
    }
}

From source file:com.intellij.codeInsight.generation.CommentByBlockCommentHandler.java

License:Apache License

@RequiredWriteAction
@Override/*w  w  w  .ja v a 2  s  . c  o m*/
public void invokeInWriteAction(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    if (!CodeInsightUtilBase.prepareEditorForWrite(editor))
        return;
    myProject = project;
    myEditor = editor;
    myFile = file;

    myDocument = editor.getDocument();

    if (!FileDocumentManager.getInstance().requestWriting(myDocument, project)) {
        return;
    }
    FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.comment.block");
    final Commenter commenter = findCommenter(myFile, myEditor);
    if (commenter == null)
        return;

    final SelectionModel selectionModel = myEditor.getSelectionModel();

    final String prefix;
    final String suffix;

    if (commenter instanceof SelfManagingCommenter) {
        final SelfManagingCommenter selfManagingCommenter = (SelfManagingCommenter) commenter;
        mySelfManagedCommenterData = selfManagingCommenter.createBlockCommentingState(
                selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), myDocument, myFile);

        if (mySelfManagedCommenterData == null) {
            mySelfManagedCommenterData = SelfManagingCommenter.EMPTY_STATE;
        }

        prefix = selfManagingCommenter.getBlockCommentPrefix(selectionModel.getSelectionStart(), myDocument,
                mySelfManagedCommenterData);
        suffix = selfManagingCommenter.getBlockCommentSuffix(selectionModel.getSelectionEnd(), myDocument,
                mySelfManagedCommenterData);
    } else {
        prefix = commenter.getBlockCommentPrefix();
        suffix = commenter.getBlockCommentSuffix();
    }

    if (prefix == null || suffix == null)
        return;

    TextRange commentedRange = findCommentedRange(commenter);
    if (commentedRange != null) {
        final int commentStart = commentedRange.getStartOffset();
        final int commentEnd = commentedRange.getEndOffset();
        int selectionStart = commentStart;
        int selectionEnd = commentEnd;
        if (selectionModel.hasSelection()) {
            selectionStart = selectionModel.getSelectionStart();
            selectionEnd = selectionModel.getSelectionEnd();
        }
        if ((commentStart < selectionStart || commentStart >= selectionEnd)
                && (commentEnd <= selectionStart || commentEnd > selectionEnd)) {
            commentRange(selectionStart, selectionEnd, prefix, suffix, commenter);
        } else {
            uncommentRange(commentedRange, trim(prefix), trim(suffix), commenter);
        }
    } else {
        if (selectionModel.hasBlockSelection()) {
            final LogicalPosition start = selectionModel.getBlockStart();
            final LogicalPosition end = selectionModel.getBlockEnd();

            assert start != null;
            assert end != null;

            int startColumn = Math.min(start.column, end.column);
            int endColumn = Math.max(start.column, end.column);
            int startLine = Math.min(start.line, end.line);
            int endLine = Math.max(start.line, end.line);

            for (int i = startLine; i <= endLine; i++) {
                editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(i, endColumn));
                EditorModificationUtil.insertStringAtCaret(editor, suffix, true, true);
            }

            for (int i = startLine; i <= endLine; i++) {
                editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(i, startColumn));
                EditorModificationUtil.insertStringAtCaret(editor, prefix, true, true);
            }
        } else if (selectionModel.hasSelection()) {
            int selectionStart = selectionModel.getSelectionStart();
            int selectionEnd = selectionModel.getSelectionEnd();
            if (commenter instanceof IndentedCommenter) {
                final Boolean value = ((IndentedCommenter) commenter).forceIndentedLineComment();
                if (value != null && value == Boolean.TRUE) {
                    selectionStart = myDocument.getLineStartOffset(myDocument.getLineNumber(selectionStart));
                    selectionEnd = myDocument.getLineEndOffset(myDocument.getLineNumber(selectionEnd));
                }
            }
            commentRange(selectionStart, selectionEnd, prefix, suffix, commenter);
        } else {
            EditorUtil.fillVirtualSpaceUntilCaret(editor);
            int caretOffset = myEditor.getCaretModel().getOffset();
            if (commenter instanceof IndentedCommenter) {
                final Boolean value = ((IndentedCommenter) commenter).forceIndentedLineComment();
                if (value != null && value == Boolean.TRUE) {
                    final int lineNumber = myDocument.getLineNumber(caretOffset);
                    final int start = myDocument.getLineStartOffset(lineNumber);
                    final int end = myDocument.getLineEndOffset(lineNumber);
                    commentRange(start, end, prefix, suffix, commenter);
                    return;
                }
            }
            myDocument.insertString(caretOffset, prefix + suffix);
            myEditor.getCaretModel().moveToOffset(caretOffset + prefix.length());
        }
    }
}

From source file:com.intellij.codeInsight.generation.surroundWith.JavaWithTryFinallySurrounder.java

License:Apache License

@Override
public TextRange surroundStatements(Project project, Editor editor, PsiElement container,
        PsiElement[] statements) throws IncorrectOperationException {
    PsiManager manager = PsiManager.getInstance(project);
    PsiElementFactory factory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);

    statements = SurroundWithUtil.moveDeclarationsOut(container, statements, false);
    if (statements.length == 0) {
        return null;
    }/*from  w  w  w . j  a  v  a2s.co m*/

    @NonNls
    String text = "try{\n}finally{\n\n}";
    PsiTryStatement tryStatement = (PsiTryStatement) factory.createStatementFromText(text, null);
    tryStatement = (PsiTryStatement) codeStyleManager.reformat(tryStatement);

    tryStatement = (PsiTryStatement) container.addAfter(tryStatement, statements[statements.length - 1]);

    PsiCodeBlock tryBlock = tryStatement.getTryBlock();
    if (tryBlock == null) {
        return null;
    }
    SurroundWithUtil.indentCommentIfNecessary(tryBlock, statements);
    tryBlock.addRange(statements[0], statements[statements.length - 1]);
    container.deleteChildRange(statements[0], statements[statements.length - 1]);

    PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
    if (finallyBlock == null) {
        return null;
    }
    int offset = finallyBlock.getTextRange().getStartOffset() + 2;
    editor.getCaretModel().moveToOffset(offset);
    final Document document = editor.getDocument();
    PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
    editor.getSelectionModel().removeSelection();
    final PsiStatement firstTryStmt = tryBlock.getStatements()[0];
    final int indent = firstTryStmt.getTextOffset()
            - document.getLineStartOffset(document.getLineNumber(firstTryStmt.getTextOffset()));
    EditorModificationUtil.insertStringAtCaret(editor, StringUtil.repeat(" ", indent), false, true);
    return new TextRange(editor.getCaretModel().getOffset(), editor.getCaretModel().getOffset());
}

From source file:com.intellij.codeInsight.template.postfix.templates.JavaPostfixTemplateProvider.java

License:Apache License

@Override
public void preExpand(@NotNull final PsiFile file, @NotNull final Editor editor) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    file.putUserData(ADDED_SEMICOLON, null);
    if (isSemicolonNeeded(file, editor)) {
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
            @Override/*from w  w w .  j a v a  2s. c o  m*/
            public void run() {
                CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
                    public void run() {
                        Document document = file.getViewProvider().getDocument();
                        assert document != null;
                        EditorModificationUtil.insertStringAtCaret(editor, ";", false, false);
                        PsiDocumentManager.getInstance(file.getProject()).commitDocument(document);
                        PsiElement at = file.findElementAt(editor.getCaretModel().getOffset());
                        if (at != null && at.getNode().getElementType() == JavaTokenType.SEMICOLON) {
                            file.putUserData(ADDED_SEMICOLON, SmartPointerManager.getInstance(file.getProject())
                                    .createSmartPsiElementPointer(at));
                        }
                    }
                });
            }
        });
    }
}

From source file:com.mnr.java.intellij.idea.plugin.base64helper.MainActionHandler.java

License:Apache License

private void processSelection(final PopupItem popupItem, final Editor editor) {
    Project[] openProjects = ProjectManager.getInstance().getOpenProjects();

    if (openProjects.length <= 0) {
        return;//www.  j av a  2 s.c om
    }

    CommandProcessor.getInstance().executeCommand(openProjects[0], new Runnable() {
        @Override
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                @Override
                public void run() {
                    if (editor == null || !editor.getDocument().isWritable()) {
                        return;
                    }

                    final String selectedText = getEditorSelectedText(editor);

                    if ((selectedText != null) && !selectedText.isEmpty()) {
                        String encodeDecode = popupItem.encodeDecode(selectedText);

                        if (encodeDecode != null) {
                            encodeDecode = encodeDecode.replace('\r', '\0');
                            EditorModificationUtil.insertStringAtCaret(editor, encodeDecode, true, true);
                        }
                    }
                }
            });
        }
    }, "Base64 Converter", null);

    FileDocumentManager.getInstance().saveAllDocuments();
}

From source file:com.perl5.lang.embedded.idea.editor.smartkeys.EmbeddedPerlSmartKeysUtil.java

License:Apache License

public static boolean addCloseMarker(@NotNull final Editor editor, @NotNull PsiFile file,
        @NotNull String marker) {
    int offset = editor.getCaretModel().getOffset();

    if (offset >= 2) {
        PsiElement element = file.findElementAt(offset - 2);
        if (element != null && element.getNode().getElementType() == EMBED_MARKER_OPEN
                && !hasCloseMarkerAhead(file, offset)) {
            EditorModificationUtil.insertStringAtCaret(editor, marker, false, false);
        }//from w  w w  .j a va 2s  .  c om
    }
    return false;
}

From source file:com.perl5.lang.mason2.idea.editor.MasonTypedHandler.java

License:Apache License

@Override
public Result charTyped(char c, final Project project, @NotNull final Editor editor, @NotNull PsiFile file) {
    if (file.getViewProvider() instanceof Mason2TemplatingFileViewProvider) {
        if (c == '>') {
            PsiElement element = file.findElementAt(editor.getCaretModel().getOffset() - 2);
            if (element != null && element.getNode().getElementType() == XML_DATA_CHARACTERS) {
                String elementText = element.getText();
                String closeTag;/*from w w  w .  j a va 2 s .  co m*/
                if ((closeTag = SIMPLE_COMPLETION_MAP.get(elementText)) != null) {
                    EditorModificationUtil.insertStringAtCaret(editor, closeTag, false, false);
                } else if (elementText.equals(KEYWORD_FLAGS_OPENER_UNCLOSED)) {
                    EditorModificationUtil.insertStringAtCaret(editor, " extends => '' " + KEYWORD_FLAGS_CLOSER,
                            false, true, 13);
                }
            }
        } else if (c == ' ') {
            PsiElement element = file.findElementAt(editor.getCaretModel().getOffset() - 2);
            if (element != null) {
                IElementType elementType = element.getNode().getElementType();
                if (elementType == MASON_BLOCK_OPENER && !isNextElement(element, MASON_BLOCK_CLOSER)) {
                    EditorModificationUtil.insertStringAtCaret(editor, KEYWORD_BLOCK_CLOSER, false, false);
                } else if (elementType == MASON_CALL_OPENER && !isNextElement(element, MASON_CALL_CLOSER)) {
                    EditorModificationUtil.insertStringAtCaret(editor, KEYWORD_CALL_CLOSER, false, false);
                } else if (elementType == MASON_METHOD_OPENER) {
                    EditorModificationUtil.insertStringAtCaret(editor, ">\n" + KEYWORD_METHOD_CLOSER, false,
                            false);
                } else if (elementType == MASON_FILTER_OPENER) {
                    EditorModificationUtil.insertStringAtCaret(editor, ">\n" + KEYWORD_FILTER_CLOSER, false,
                            false);
                } else if (elementType == MASON_OVERRIDE_OPENER) {
                    EditorModificationUtil.insertStringAtCaret(editor, ">\n" + KEYWORD_OVERRIDE_CLOSER, false,
                            false);
                }
            }
        } else if (c == '{') {
            int offset = editor.getCaretModel().getOffset();
            PsiElement element = file.findElementAt(offset - 2);
            if (element != null && element.getNode().getElementType() == LEFT_BRACE) {
                Document document = editor.getDocument();
                int lineNumber = document.getLineNumber(offset - 1);
                PsiElement lineStartElement = file.findElementAt(document.getLineStartOffset(lineNumber));

                if (lineStartElement != null
                        && lineStartElement.getNode().getElementType() == MASON_LINE_OPENER) {
                    PsiElement nextElement = file.findElementAt(offset - 1);
                    if (nextElement != null && nextElement.getNode().getElementType() == RIGHT_BRACE) {
                        EditorModificationUtil.insertStringAtCaret(editor, "\n\n% ", false, true, 1);
                    }
                }
            }
        }

    }
    return super.charTyped(c, project, editor, file);
}

From source file:com.perl5.lang.mojolicious.idea.editor.smartkeys.MojoliciousSmartKeysUtil.java

License:Apache License

public static boolean addCloseMarker(@NotNull final Editor editor, @NotNull PsiFile file,
        @NotNull String marker) {
    PsiElement element = file.findElementAt(editor.getCaretModel().getOffset() - 2);
    IElementType elementType = PsiUtilCore.getElementType(element);
    if (elementType == MOJO_BLOCK_OPENER || elementType == MOJO_BLOCK_EXPR_OPENER
            || elementType == MOJO_BLOCK_EXPR_ESCAPED_OPENER) {
        ASTNode nextSibling = PerlPsiUtil.getNextSignificantSibling(element.getNode());
        if (nextSibling == null || !CLOSE_TOKENS.contains(nextSibling.getElementType())) {
            EditorModificationUtil.insertStringAtCaret(editor, marker, false, false);
            return true;
        }//from www.  java  2 s. c o m
    }
    return false;
}