Search in sources :

Example 41 with PsiDocumentManager

use of com.intellij.psi.PsiDocumentManager in project intellij-community by JetBrains.

the class CodeStyleSettingsManager method updateDocumentIndentOptions.

/**
   * Updates document's indent options from indent options providers.
   * <p><b>Note:</b> Calling this method directly when there is an editor associated with the document may cause the editor work
   * incorrectly. To keep consistency with the editor call {@code EditorEx.reinitSettings()} instead.
   * @param project  The project of the document.
   * @param document The document to update indent options for.
   */
public static void updateDocumentIndentOptions(@NotNull Project project, @NotNull Document document) {
    if (!project.isDisposed()) {
        PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
        if (documentManager != null) {
            PsiFile file = documentManager.getPsiFile(document);
            if (file != null) {
                CommonCodeStyleSettings.IndentOptions indentOptions = getSettings(project).getIndentOptionsByFile(file, null, true, null);
                indentOptions.associateWithDocument(document);
            }
        }
    }
}
Also used : PsiFile(com.intellij.psi.PsiFile) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 42 with PsiDocumentManager

use of com.intellij.psi.PsiDocumentManager in project intellij-community by JetBrains.

the class RearrangeCodeAction method actionPerformed.

@Override
public void actionPerformed(AnActionEvent e) {
    final Project project = e.getProject();
    if (project == null) {
        return;
    }
    final Editor editor = e.getData(CommonDataKeys.EDITOR);
    if (editor == null) {
        return;
    }
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    Document document = editor.getDocument();
    documentManager.commitDocument(document);
    final PsiFile file = documentManager.getPsiFile(document);
    if (file == null) {
        return;
    }
    SelectionModel model = editor.getSelectionModel();
    if (model.hasSelection()) {
        new RearrangeCodeProcessor(file, model).run();
    } else {
        new RearrangeCodeProcessor(file).run();
    }
}
Also used : RearrangeCodeProcessor(com.intellij.codeInsight.actions.RearrangeCodeProcessor) Project(com.intellij.openapi.project.Project) SelectionModel(com.intellij.openapi.editor.SelectionModel) PsiFile(com.intellij.psi.PsiFile) Editor(com.intellij.openapi.editor.Editor) Document(com.intellij.openapi.editor.Document) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 43 with PsiDocumentManager

use of com.intellij.psi.PsiDocumentManager in project intellij-community by JetBrains.

the class TypedHandler method indentBrace.

private static void indentBrace(@NotNull final Project project, @NotNull final Editor editor, final char braceChar) {
    final int offset = editor.getCaretModel().getOffset() - 1;
    final Document document = editor.getDocument();
    CharSequence chars = document.getCharsSequence();
    if (offset < 0 || chars.charAt(offset) != braceChar)
        return;
    int spaceStart = CharArrayUtil.shiftBackward(chars, offset - 1, " \t");
    if (spaceStart < 0 || chars.charAt(spaceStart) == '\n' || chars.charAt(spaceStart) == '\r') {
        PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
        documentManager.commitDocument(document);
        final PsiFile file = documentManager.getPsiFile(document);
        if (file == null || !file.isWritable())
            return;
        PsiElement element = file.findElementAt(offset);
        if (element == null)
            return;
        EditorHighlighter highlighter = ((EditorEx) editor).getHighlighter();
        HighlighterIterator iterator = highlighter.createIterator(offset);
        final FileType fileType = file.getFileType();
        BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);
        boolean rBraceToken = braceMatcher.isRBraceToken(iterator, chars, fileType);
        final boolean isBrace = braceMatcher.isLBraceToken(iterator, chars, fileType) || rBraceToken;
        int lBraceOffset = -1;
        if (CodeInsightSettings.getInstance().REFORMAT_BLOCK_ON_RBRACE && rBraceToken && braceMatcher.isStructuralBrace(iterator, chars, fileType) && offset > 0) {
            lBraceOffset = BraceMatchingUtil.findLeftLParen(highlighter.createIterator(offset - 1), braceMatcher.getOppositeBraceTokenType(iterator.getTokenType()), editor.getDocument().getCharsSequence(), fileType);
        }
        if (element.getNode() != null && isBrace) {
            final int finalLBraceOffset = lBraceOffset;
            ApplicationManager.getApplication().runWriteAction(() -> {
                try {
                    int newOffset;
                    if (finalLBraceOffset != -1) {
                        RangeMarker marker = document.createRangeMarker(offset, offset + 1);
                        CodeStyleManager.getInstance(project).reformatRange(file, finalLBraceOffset, offset, true);
                        newOffset = marker.getStartOffset();
                        marker.dispose();
                    } else {
                        newOffset = CodeStyleManager.getInstance(project).adjustLineIndent(file, offset);
                    }
                    editor.getCaretModel().moveToOffset(newOffset + 1);
                    editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
                    editor.getSelectionModel().removeSelection();
                } catch (IncorrectOperationException e) {
                    LOG.error(e);
                }
            });
        }
    }
}
Also used : EditorEx(com.intellij.openapi.editor.ex.EditorEx) NontrivialBraceMatcher(com.intellij.codeInsight.highlighting.NontrivialBraceMatcher) BraceMatcher(com.intellij.codeInsight.highlighting.BraceMatcher) FileType(com.intellij.openapi.fileTypes.FileType) LanguageFileType(com.intellij.openapi.fileTypes.LanguageFileType) PsiFile(com.intellij.psi.PsiFile) IncorrectOperationException(com.intellij.util.IncorrectOperationException) PsiElement(com.intellij.psi.PsiElement) HighlighterIterator(com.intellij.openapi.editor.highlighter.HighlighterIterator) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) EditorHighlighter(com.intellij.openapi.editor.highlighter.EditorHighlighter)

Example 44 with PsiDocumentManager

use of com.intellij.psi.PsiDocumentManager in project intellij-community by JetBrains.

the class TypedHandler method execute.

@Override
public void execute(@NotNull final Editor originalEditor, final char charTyped, @NotNull final DataContext dataContext) {
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    final PsiFile originalFile;
    if (project == null || (originalFile = PsiUtilBase.getPsiFileInEditor(originalEditor, project)) == null) {
        if (myOriginalHandler != null) {
            myOriginalHandler.execute(originalEditor, charTyped, dataContext);
        }
        return;
    }
    if (!EditorModificationUtil.checkModificationAllowed(originalEditor))
        return;
    final PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
    final Document originalDocument = originalEditor.getDocument();
    originalEditor.getCaretModel().runForEachCaret(new CaretAction() {

        @Override
        public void perform(Caret caret) {
            if (psiDocumentManager.isDocumentBlockedByPsi(originalDocument)) {
                // to clean up after previous caret processing
                psiDocumentManager.doPostponedOperationsAndUnblockDocument(originalDocument);
            }
            Editor editor = injectedEditorIfCharTypedIsSignificant(charTyped, originalEditor, originalFile);
            PsiFile file = editor == originalEditor ? originalFile : psiDocumentManager.getPsiFile(editor.getDocument());
            final TypedHandlerDelegate[] delegates = Extensions.getExtensions(TypedHandlerDelegate.EP_NAME);
            if (caret == originalEditor.getCaretModel().getPrimaryCaret()) {
                boolean handled = false;
                for (TypedHandlerDelegate delegate : delegates) {
                    final TypedHandlerDelegate.Result result = delegate.checkAutoPopup(charTyped, project, editor, file);
                    handled = result == TypedHandlerDelegate.Result.STOP;
                    if (result != TypedHandlerDelegate.Result.CONTINUE) {
                        break;
                    }
                }
                if (!handled) {
                    autoPopupCompletion(editor, charTyped, project, file);
                    autoPopupParameterInfo(editor, charTyped, project, file);
                }
            }
            if (!editor.isInsertMode()) {
                type(originalEditor, charTyped);
                return;
            }
            for (TypedHandlerDelegate delegate : delegates) {
                final TypedHandlerDelegate.Result result = delegate.beforeSelectionRemoved(charTyped, project, editor, file);
                if (result == TypedHandlerDelegate.Result.STOP) {
                    return;
                }
                if (result == TypedHandlerDelegate.Result.DEFAULT) {
                    break;
                }
            }
            EditorModificationUtil.deleteSelectedText(editor);
            FileType fileType = getFileType(file, editor);
            for (TypedHandlerDelegate delegate : delegates) {
                final TypedHandlerDelegate.Result result = delegate.beforeCharTyped(charTyped, project, editor, file, fileType);
                if (result == TypedHandlerDelegate.Result.STOP) {
                    return;
                }
                if (result == TypedHandlerDelegate.Result.DEFAULT) {
                    break;
                }
            }
            if (')' == charTyped || ']' == charTyped || '}' == charTyped) {
                if (FileTypes.PLAIN_TEXT != fileType) {
                    if (handleRParen(editor, fileType, charTyped))
                        return;
                }
            } else if ('"' == charTyped || '\'' == charTyped || '`' == charTyped) /* || '/' == charTyped*/
            {
                if (handleQuote(editor, charTyped, file))
                    return;
            }
            long modificationStampBeforeTyping = editor.getDocument().getModificationStamp();
            type(originalEditor, charTyped);
            AutoHardWrapHandler.getInstance().wrapLineIfNecessary(originalEditor, dataContext, modificationStampBeforeTyping);
            if (('(' == charTyped || '[' == charTyped || '{' == charTyped) && CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET && fileType != FileTypes.PLAIN_TEXT) {
                handleAfterLParen(editor, fileType, charTyped);
            } else if ('}' == charTyped) {
                indentClosingBrace(project, editor);
            } else if (')' == charTyped) {
                indentClosingParenth(project, editor);
            }
            for (TypedHandlerDelegate delegate : delegates) {
                final TypedHandlerDelegate.Result result = delegate.charTyped(charTyped, project, editor, file);
                if (result == TypedHandlerDelegate.Result.STOP) {
                    return;
                }
                if (result == TypedHandlerDelegate.Result.DEFAULT) {
                    break;
                }
            }
            if ('{' == charTyped) {
                indentOpenedBrace(project, editor);
            } else if ('(' == charTyped) {
                indentOpenedParenth(project, editor);
            }
        }
    });
}
Also used : Project(com.intellij.openapi.project.Project) FileType(com.intellij.openapi.fileTypes.FileType) LanguageFileType(com.intellij.openapi.fileTypes.LanguageFileType) PsiFile(com.intellij.psi.PsiFile) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 45 with PsiDocumentManager

use of com.intellij.psi.PsiDocumentManager in project intellij-community by JetBrains.

the class DuplocatorHashCallback method writeFragments.

@SuppressWarnings({ "HardCodedStringLiteral" })
private static void writeFragments(final List<PsiFragment> psiFragments, final PrettyPrintWriter writer, Project project, final boolean shouldWriteOffsets) {
    final PathMacroManager macroManager = PathMacroManager.getInstance(project);
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    for (PsiFragment fragment : psiFragments) {
        final PsiFile psiFile = fragment.getFile();
        final VirtualFile virtualFile = psiFile != null ? psiFile.getVirtualFile() : null;
        if (virtualFile != null) {
            writer.startNode("fragment");
            writer.addAttribute("file", macroManager.collapsePath(virtualFile.getUrl()));
            if (shouldWriteOffsets) {
                final Document document = documentManager.getDocument(psiFile);
                LOG.assertTrue(document != null);
                int startOffset = fragment.getStartOffset();
                final int line = document.getLineNumber(startOffset);
                writer.addAttribute("line", String.valueOf(line));
                final int lineStartOffset = document.getLineStartOffset(line);
                if (StringUtil.isEmptyOrSpaces(document.getText().substring(lineStartOffset, startOffset))) {
                    startOffset = lineStartOffset;
                }
                writer.addAttribute("start", String.valueOf(startOffset));
                writer.addAttribute("end", String.valueOf(fragment.getEndOffset()));
                if (fragment.containsMultipleFragments()) {
                    final int[][] offsets = fragment.getOffsets();
                    for (int[] offset : offsets) {
                        writer.startNode("offset");
                        writer.addAttribute("start", String.valueOf(offset[0]));
                        writer.addAttribute("end", String.valueOf(offset[1]));
                        writer.endNode();
                    }
                }
            }
            writer.endNode();
        }
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) PsiFragment(com.intellij.dupLocator.util.PsiFragment) PsiFile(com.intellij.psi.PsiFile) PathMacroManager(com.intellij.openapi.components.PathMacroManager) Document(com.intellij.openapi.editor.Document) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Aggregations

PsiDocumentManager (com.intellij.psi.PsiDocumentManager)140 Document (com.intellij.openapi.editor.Document)111 PsiFile (com.intellij.psi.PsiFile)100 VirtualFile (com.intellij.openapi.vfs.VirtualFile)51 ResourceItem (com.android.ide.common.res2.ResourceItem)26 PsiElement (com.intellij.psi.PsiElement)24 Project (com.intellij.openapi.project.Project)22 TextRange (com.intellij.openapi.util.TextRange)13 NotNull (org.jetbrains.annotations.NotNull)12 Nullable (org.jetbrains.annotations.Nullable)9 IncorrectOperationException (com.intellij.util.IncorrectOperationException)8 Editor (com.intellij.openapi.editor.Editor)7 XmlFile (com.intellij.psi.xml.XmlFile)6 FileType (com.intellij.openapi.fileTypes.FileType)5 XmlTag (com.intellij.psi.xml.XmlTag)5 ASTNode (com.intellij.lang.ASTNode)3 GroovyPsiElementFactory (org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory)3 WriteCommandAction (com.intellij.openapi.command.WriteCommandAction)2 DocumentEx (com.intellij.openapi.editor.ex.DocumentEx)2 EditorEx (com.intellij.openapi.editor.ex.EditorEx)2