Search in sources :

Example 11 with PsiDocumentManager

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

the class PyTrailingBlankLinesPostFormatProcessor method replaceOrDeleteTrailingWhitespaces.

@NotNull
private static TextRange replaceOrDeleteTrailingWhitespaces(@NotNull final PsiFile pyFile, @NotNull final TextRange whitespaceRange) {
    final Project project = pyFile.getProject();
    final PyCodeStyleSettings customSettings = CodeStyleSettingsManager.getSettings(project).getCustomSettings(PyCodeStyleSettings.class);
    final boolean addLineFeed = customSettings.BLANK_LINE_AT_FILE_END || EditorSettingsExternalizable.getInstance().isEnsureNewLineAtEOF();
    final String realWhitespace = whitespaceRange.substring(pyFile.getText());
    final String desiredWhitespace = addLineFeed ? "\n" : "";
    // Do not add extra blank line in empty file
    if (!realWhitespace.equals(desiredWhitespace) && (desiredWhitespace.isEmpty() || whitespaceRange.getStartOffset() != 0)) {
        final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
        final Document document = documentManager.getDocument(pyFile);
        if (document != null) {
            documentManager.doPostponedOperationsAndUnblockDocument(document);
            try {
                document.replaceString(whitespaceRange.getStartOffset(), whitespaceRange.getEndOffset(), desiredWhitespace);
                return TextRange.from(whitespaceRange.getStartOffset(), desiredWhitespace.length());
            } finally {
                documentManager.commitDocument(document);
            }
        }
    }
    return whitespaceRange;
}
Also used : Project(com.intellij.openapi.project.Project) Document(com.intellij.openapi.editor.Document) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) NotNull(org.jetbrains.annotations.NotNull)

Example 12 with PsiDocumentManager

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

the class PyDocstringGenerator method buildAndInsert.

@NotNull
public PyDocStringOwner buildAndInsert() {
    Preconditions.checkNotNull(myDocStringOwner, "For this action docstring owner must be supplied");
    final String replacementText = buildDocString();
    final Project project = myDocStringOwner.getProject();
    PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project);
    final PyExpressionStatement replacement = elementGenerator.createDocstring(replacementText);
    final PyStringLiteralExpression docStringExpression = getDocStringExpression();
    if (docStringExpression != null) {
        docStringExpression.replace(replacement.getExpression());
    } else {
        PyStatementListContainer container = PyUtil.as(myDocStringOwner, PyStatementListContainer.class);
        if (container == null) {
            throw new IllegalStateException("Should be a function or class");
        }
        final PyStatementList statements = container.getStatementList();
        final String indentation = PyIndentUtil.getElementIndent(statements);
        final Document document = PsiDocumentManager.getInstance(project).getDocument(myDocStringOwner.getContainingFile());
        if (document != null) {
            final PsiElement beforeStatements = statements.getPrevSibling();
            final boolean onSameLine = !(beforeStatements instanceof PsiWhiteSpace) || !beforeStatements.textContains('\n');
            if (onSameLine || statements.getStatements().length == 0) {
                String replacementWithLineBreaks = "\n" + indentation + replacementText;
                if (statements.getStatements().length > 0) {
                    replacementWithLineBreaks += "\n" + indentation;
                }
                final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
                documentManager.doPostponedOperationsAndUnblockDocument(document);
                final TextRange range = beforeStatements.getTextRange();
                try {
                    if (beforeStatements instanceof PsiWhiteSpace) {
                        if (statements.getStatements().length > 0) {
                            document.replaceString(range.getStartOffset(), range.getEndOffset(), replacementWithLineBreaks);
                        } else {
                            // preserve original spacing, since it probably separates function and other declarations
                            document.insertString(range.getStartOffset(), replacementWithLineBreaks);
                        }
                    } else {
                        document.insertString(range.getEndOffset(), replacementWithLineBreaks);
                    }
                } finally {
                    documentManager.commitDocument(document);
                }
            } else {
                statements.addBefore(replacement, statements.getStatements()[0]);
            }
        }
    }
    myDocStringOwner = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(myDocStringOwner);
    return myDocStringOwner;
}
Also used : TextRange(com.intellij.openapi.util.TextRange) Document(com.intellij.openapi.editor.Document) Project(com.intellij.openapi.project.Project) PsiElement(com.intellij.psi.PsiElement) PsiWhiteSpace(com.intellij.psi.PsiWhiteSpace) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) NotNull(org.jetbrains.annotations.NotNull)

Example 13 with PsiDocumentManager

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

the class TextEditorHighlightingPassRegistrarImpl method instantiatePasses.

@Override
@NotNull
public List<TextEditorHighlightingPass> instantiatePasses(@NotNull final PsiFile psiFile, @NotNull final Editor editor, @NotNull final int[] passesToIgnore) {
    synchronized (this) {
        if (!checkedForCycles) {
            checkedForCycles = true;
            checkForCycles();
        }
    }
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    final Document document = editor.getDocument();
    PsiFile fileFromDoc = documentManager.getPsiFile(document);
    if (!(fileFromDoc instanceof PsiCompiledElement)) {
        assert fileFromDoc == psiFile : "Files are different: " + psiFile + ";" + fileFromDoc;
        Document documentFromFile = documentManager.getDocument(psiFile);
        assert documentFromFile == document : "Documents are different. Doc: " + document + "; Doc from file: " + documentFromFile + "; File: " + psiFile + "; Virtual file: " + PsiUtilCore.getVirtualFile(psiFile);
    }
    final TIntObjectHashMap<TextEditorHighlightingPass> id2Pass = new TIntObjectHashMap<>();
    final TIntArrayList passesRefusedToCreate = new TIntArrayList();
    myRegisteredPassFactories.forEachKey(passId -> {
        if (ArrayUtil.find(passesToIgnore, passId) != -1) {
            return true;
        }
        PassConfig passConfig = myRegisteredPassFactories.get(passId);
        TextEditorHighlightingPassFactory factory = passConfig.passFactory;
        final TextEditorHighlightingPass pass = factory.createHighlightingPass(psiFile, editor);
        if (pass == null) {
            passesRefusedToCreate.add(passId);
        } else {
            pass.setColorsScheme(editor.getColorsScheme());
            TIntArrayList ids = new TIntArrayList(passConfig.completionPredecessorIds.length);
            for (int id : passConfig.completionPredecessorIds) {
                if (myRegisteredPassFactories.containsKey(id))
                    ids.add(id);
            }
            pass.setCompletionPredecessorIds(ids.isEmpty() ? ArrayUtil.EMPTY_INT_ARRAY : ids.toNativeArray());
            ids = new TIntArrayList(passConfig.startingPredecessorIds.length);
            for (int id : passConfig.startingPredecessorIds) {
                if (myRegisteredPassFactories.containsKey(id))
                    ids.add(id);
            }
            pass.setStartingPredecessorIds(ids.isEmpty() ? ArrayUtil.EMPTY_INT_ARRAY : ids.toNativeArray());
            pass.setId(passId);
            id2Pass.put(passId, pass);
        }
        return true;
    });
    DaemonCodeAnalyzerEx daemonCodeAnalyzer = DaemonCodeAnalyzerEx.getInstanceEx(myProject);
    final FileStatusMap statusMap = daemonCodeAnalyzer.getFileStatusMap();
    passesRefusedToCreate.forEach(passId -> {
        statusMap.markFileUpToDate(document, passId);
        return true;
    });
    return (List) Arrays.asList(id2Pass.getValues());
}
Also used : PsiCompiledElement(com.intellij.psi.PsiCompiledElement) Document(com.intellij.openapi.editor.Document) PsiFile(com.intellij.psi.PsiFile) ArrayList(java.util.ArrayList) List(java.util.List) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) NotNull(org.jetbrains.annotations.NotNull)

Example 14 with PsiDocumentManager

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

the class UsageViewTest method testUsageViewCanRerunAfterTargetWasInvalidatedAndRestored.

public void testUsageViewCanRerunAfterTargetWasInvalidatedAndRestored() throws Exception {
    PsiFile psiFile = myFixture.addFileToProject("X.java", "public class X{" + "    void foo() {\n" + "        bar();\n" + "        bar();\n" + "    }" + "    void bar() {}\n" + "}");
    Usage usage = createUsage(psiFile, psiFile.getText().indexOf("bar();"));
    PsiElement[] members = psiFile.getChildren()[psiFile.getChildren().length - 1].getChildren();
    PsiNamedElement bar = (PsiNamedElement) members[members.length - 3];
    assertEquals("bar", bar.getName());
    UsageTarget target = new PsiElement2UsageTargetAdapter(bar);
    FindUsagesManager usagesManager = ((FindManagerImpl) FindManager.getInstance(getProject())).getFindUsagesManager();
    FindUsagesHandler handler = usagesManager.getNewFindUsagesHandler(bar, false);
    UsageViewImpl usageView = (UsageViewImpl) usagesManager.doFindUsages(new PsiElement[] { bar }, PsiElement.EMPTY_ARRAY, handler, handler.getFindUsagesOptions(), false);
    Disposer.register(myFixture.getTestRootDisposable(), usageView);
    assertTrue(usageView.canPerformReRun());
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
    Document document = documentManager.getDocument(psiFile);
    String barDef = "void bar() {}\n";
    String commentedBarDef = "//" + barDef;
    WriteCommandAction.runWriteCommandAction(getProject(), () -> {
        String text = document.getText();
        document.replaceString(text.indexOf(barDef), text.indexOf(barDef) + barDef.length(), commentedBarDef);
    });
    documentManager.commitAllDocuments();
    // target invalidated
    assertFalse(usageView.canPerformReRun());
    WriteCommandAction.runWriteCommandAction(getProject(), () -> {
        String text = document.getText();
        document.replaceString(text.indexOf(commentedBarDef), text.indexOf(commentedBarDef) + commentedBarDef.length(), barDef);
    });
    documentManager.commitAllDocuments();
    assertTrue(usageView.canPerformReRun());
    usageView.doReRun();
    Set<Usage> usages = usageView.getUsages();
    assertEquals(2, usages.size());
}
Also used : FindUsagesHandler(com.intellij.find.findUsages.FindUsagesHandler) PsiNamedElement(com.intellij.psi.PsiNamedElement) PsiElement2UsageTargetAdapter(com.intellij.find.findUsages.PsiElement2UsageTargetAdapter) Document(com.intellij.openapi.editor.Document) FindManagerImpl(com.intellij.find.impl.FindManagerImpl) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement) FindUsagesManager(com.intellij.find.findUsages.FindUsagesManager) PsiDocumentManager(com.intellij.psi.PsiDocumentManager)

Example 15 with PsiDocumentManager

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

the class UsageViewTest method testTextUsageInfoHandlesDocumentChange.

public void testTextUsageInfoHandlesDocumentChange() throws Exception {
    PsiFile psiFile = myFixture.addFileToProject("X.java", "public class X{ int xxx; } //comment");
    Usage usage = new UsageInfo2UsageAdapter(new UsageInfo(psiFile, psiFile.getText().indexOf("xxx"), StringUtil.indexOfSubstringEnd(psiFile.getText(), "xxx")));
    UsageView usageView = UsageViewManager.getInstance(getProject()).createUsageView(UsageTarget.EMPTY_ARRAY, new Usage[] { usage }, new UsageViewPresentation(), null);
    Disposer.register(myFixture.getTestRootDisposable(), usageView);
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
    Document document = documentManager.getDocument(psiFile);
    WriteCommandAction.runWriteCommandAction(getProject(), () -> document.insertString(0, "/* sdfsdfsd */"));
    documentManager.commitAllDocuments();
    int navigationOffset = ((UsageInfo2UsageAdapter) usage).getUsageInfo().getNavigationOffset();
    assertEquals(psiFile.getText().indexOf("xxx"), navigationOffset);
}
Also used : PsiFile(com.intellij.psi.PsiFile) Document(com.intellij.openapi.editor.Document) UsageInfo(com.intellij.usageView.UsageInfo) 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