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;
}
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;
}
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());
}
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());
}
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);
}
Aggregations