private void createNameAndReturnTypeEditors() { myNameCodeFragment = new GroovyCodeFragment(myProject, ""); myNameField = new EditorTextField( PsiDocumentManager.getInstance(myProject).getDocument(myNameCodeFragment), myProject, myNameCodeFragment.getFileType()); final JavaCodeFragmentFactory factory = JavaCodeFragmentFactory.getInstance(myProject); myReturnTypeCodeFragment = factory.createTypeCodeFragment("", myMethod, true, JavaCodeFragmentFactory.ALLOW_VOID); final Document document = PsiDocumentManager.getInstance(myProject).getDocument(myReturnTypeCodeFragment); myReturnTypeField = new EditorTextField(document, myProject, myReturnTypeCodeFragment.getFileType()); myNameField.setText(myMethod.getName()); final GrTypeElement element = myMethod.getReturnTypeElementGroovy(); if (element != null) { myReturnTypeField.setText(element.getText()); } myReturnTypeLabel = new JLabel(); myReturnTypeLabel.setLabelFor(myReturnTypeField); myNameLabel = new JLabel(); myNameLabel.setLabelFor(myNameField); }
public void testTypingDoesNotInterfereWithDuplicates() throws Exception { SliceTreeStructure treeStructure = configureTree("DupSlice"); SliceNode root = (SliceNode) treeStructure.getRootElement(); List<SliceNode> nodes = new ArrayList<SliceNode>(); expandNodesTo(root, nodes); for (int i = 0; i < nodes.size() - 1; i++) { SliceNode node = nodes.get(i); assertNull(node.getDuplicate()); } SliceNode last = nodes.get(nodes.size() - 1); assertNotNull(last.getDuplicate()); type(" xx"); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); backspace(); backspace(); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); nodes.clear(); expandNodesTo(root, nodes); for (int i = 0; i < nodes.size() - 1; i++) { SliceNode node = nodes.get(i); assertNull(node.getDuplicate()); } assertNotNull(last.getDuplicate()); }
void execute(BrowseMode browseMode) { myBrowseMode = browseMode; Document document = myEditor.getDocument(); final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document); if (file == null) return; PsiDocumentManager.getInstance(myProject).commitAllDocuments(); if (EditorUtil.inVirtualSpace(myEditor, myPosition)) { return; } final int offset = myEditor.logicalPositionToOffset(myPosition); int selStart = myEditor.getSelectionModel().getSelectionStart(); int selEnd = myEditor.getSelectionModel().getSelectionEnd(); if (offset >= selStart && offset < selEnd) return; ProgressIndicatorUtils.scheduleWithWriteActionPriority( myProgress, new ReadTask() { @Override public void computeInReadAction(@NotNull ProgressIndicator indicator) { doExecute(file, offset); } @Override public void onCanceled(@NotNull ProgressIndicator indicator) {} }); }
public void execute(BrowseMode browseMode) { myBrowseMode = browseMode; Document document = myEditor.getDocument(); final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document); if (file == null) return; PsiDocumentManager.getInstance(myProject).commitAllDocuments(); if (TargetElementUtilBase.inVirtualSpace(myEditor, myPosition)) { return; } final int offset = myEditor.logicalPositionToOffset(myPosition); int selStart = myEditor.getSelectionModel().getSelectionStart(); int selEnd = myEditor.getSelectionModel().getSelectionEnd(); if (offset >= selStart && offset < selEnd) return; ApplicationManager.getApplication() .executeOnPooledThread( new Runnable() { public void run() { final ProgressIndicator progressIndicator = new ProgressIndicatorBase(); final ApplicationAdapter listener = new ApplicationAdapter() { @Override public void beforeWriteActionStart(Object action) { progressIndicator.cancel(); } }; final Application application = ApplicationManager.getApplication(); try { application.addApplicationListener(listener); ProgressManager.getInstance() .runProcess( new Runnable() { @Override public void run() { // This read action can possibe last for a long time, we want it to // stop immediately on the first write access. // For this purpose we launch it under empty progress and invoke // progressIndicator#cancel on write access to avoid possible write // lock delays. application.runReadAction( new Runnable() { public void run() { doExecute(file, offset); } }); } }, progressIndicator); } finally { application.removeApplicationListener(listener); } } }); }
private void altCommitToOriginal(@NotNull DocumentEvent e) { final PsiFile origPsiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument); String newText = myNewDocument.getText(); // prepare guarded blocks LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>(); int count = 0; for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) { String replacement = o.getUserData(REPLACEMENT_KEY); String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement)); newText = newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset()); replacementMap.put(tempText, replacement); } // run preformat processors final int hostStartOffset = myAltFullRange.getStartOffset(); myEditor.getCaretModel().moveToOffset(hostStartOffset); for (CopyPastePreProcessor preProcessor : Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) { newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null); } myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText); // replace temp strings for guarded blocks for (String tempText : replacementMap.keySet()) { int idx = CharArrayUtil.indexOf( myOrigDocument.getCharsSequence(), tempText, hostStartOffset, myAltFullRange.getEndOffset()); myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText)); } // JAVA: fix occasional char literal concatenation fixDocumentQuotes(myOrigDocument, hostStartOffset - 1); fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset()); // reformat PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument); Runnable task = () -> { try { CodeStyleManager.getInstance(myProject) .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true); } catch (IncorrectOperationException e1) { // LOG.error(e); } }; DocumentUtil.executeInBulk(myOrigDocument, true, task); PsiElement newInjected = InjectedLanguageManager.getInstance(myProject) .findInjectedElementAt(origPsiFile, hostStartOffset); DocumentWindow documentWindow = newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected); if (documentWindow != null) { myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset())); myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE); } }
@Nullable private KtNamedDeclaration[] getVariables(Expression[] params, ExpressionContext context) { if (params.length != 0) return null; Project project = context.getProject(); PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(context.getEditor().getDocument()); if (!(psiFile instanceof KtFile)) return null; KtExpression contextExpression = findContextExpression(psiFile, context.getStartOffset()); if (contextExpression == null) return null; ResolutionFacade resolutionFacade = ResolutionUtils.getResolutionFacade(contextExpression); BindingContext bindingContext = resolutionFacade.analyze(contextExpression, BodyResolveMode.FULL); LexicalScope scope = ScopeUtils.getResolutionScope(contextExpression, bindingContext, resolutionFacade); IterableTypesDetector detector = resolutionFacade.getIdeService(IterableTypesDetection.class).createDetector(scope); DataFlowInfo dataFlowInfo = BindingContextUtilsKt.getDataFlowInfo(bindingContext, contextExpression); List<VariableDescriptor> filteredDescriptors = new ArrayList<VariableDescriptor>(); for (DeclarationDescriptor declarationDescriptor : getAllVariables(scope)) { if (declarationDescriptor instanceof VariableDescriptor) { VariableDescriptor variableDescriptor = (VariableDescriptor) declarationDescriptor; if (variableDescriptor.getExtensionReceiverParameter() != null && ExtensionUtils.substituteExtensionIfCallableWithImplicitReceiver( variableDescriptor, scope, bindingContext, dataFlowInfo) .isEmpty()) { continue; } if (isSuitable(variableDescriptor, project, detector)) { filteredDescriptors.add(variableDescriptor); } } } List<KtNamedDeclaration> declarations = new ArrayList<KtNamedDeclaration>(); for (DeclarationDescriptor declarationDescriptor : filteredDescriptors) { PsiElement declaration = DescriptorToSourceUtils.descriptorToDeclaration(declarationDescriptor); assert declaration == null || declaration instanceof PsiNamedElement; if (declaration instanceof KtProperty || declaration instanceof KtParameter) { declarations.add((KtNamedDeclaration) declaration); } } return declarations.toArray(new KtNamedDeclaration[declarations.size()]); }
protected static void bringRealEditorBack() { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); if (myEditor instanceof EditorWindow) { Document document = ((DocumentWindow) myEditor.getDocument()).getDelegate(); myFile = PsiDocumentManager.getInstance(getProject()).getPsiFile(document); myEditor = ((EditorWindow) myEditor).getDelegate(); myVFile = myFile.getVirtualFile(); } }
@Nullable public static Document getDocumentToBeUsedFor(final PsiFile file) { final Project project = file.getProject(); final Document document = PsiDocumentManager.getInstance(project).getDocument(file); if (document == null) return null; if (PsiDocumentManager.getInstance(project).isUncommited(document)) return null; PsiToDocumentSynchronizer synchronizer = ((PsiDocumentManagerImpl) PsiDocumentManager.getInstance(project)).getSynchronizer(); if (synchronizer.isDocumentAffectedByTransactions(document)) return null; return document; }
@Nullable private PsiComment createComment(final CharSequence buffer, final CodeInsightSettings settings) throws IncorrectOperationException { myDocument.insertString(myOffset, buffer); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); CodeStyleManager.getInstance(getProject()) .adjustLineIndent(myFile, myOffset + buffer.length() - 2); PsiComment comment = PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class); comment = createJavaDocStub(settings, comment, getProject()); if (comment == null) { return null; } CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject()); CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject()); boolean old = codeStyleSettings.ENABLE_JAVADOC_FORMATTING; codeStyleSettings.ENABLE_JAVADOC_FORMATTING = false; try { comment = (PsiComment) codeStyleManager.reformat(comment); } finally { codeStyleSettings.ENABLE_JAVADOC_FORMATTING = old; } PsiElement next = comment.getNextSibling(); if (next == null && comment.getParent().getClass() == comment.getClass()) { next = comment .getParent() .getNextSibling(); // expanding chameleon comment produces comment under comment } if (next != null) { next = myFile.findElementAt( next.getTextRange().getStartOffset()); // maybe switch to another tree } if (next != null && (!FormatterUtil.containsWhiteSpacesOnly(next.getNode()) || !next.getText().contains(LINE_SEPARATOR))) { int lineBreakOffset = comment.getTextRange().getEndOffset(); myDocument.insertString(lineBreakOffset, LINE_SEPARATOR); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); codeStyleManager.adjustLineIndent(myFile, lineBreakOffset + 1); comment = PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class); } return comment; }
protected void doTest(final PerformAction performAction, final String testName) throws Exception { String path = getTestDataPath() + getTestRoot() + testName; String pathBefore = path + "/before"; final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure( myProject, myModule, pathBefore, myFilesToDelete, false); prepareProject(rootDir); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); String pathAfter = path + "/after"; final VirtualFile rootAfter = LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/')); performAction.performAction(rootDir, rootAfter); ApplicationManager.getApplication() .runWriteAction( new Runnable() { public void run() { myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting(); } }); FileDocumentManager.getInstance().saveAllDocuments(); if (myDoCompare) { PlatformTestUtil.assertDirectoriesEqual(rootAfter, rootDir); } }
private boolean getStringToReplace( int textOffset, int textEndOffset, Document document, FindModel findModel, Ref<String> stringToReplace) throws FindManager.MalformedReplacementStringException { if (textOffset < 0 || textOffset >= document.getTextLength()) { return false; } if (textEndOffset < 0 || textOffset > document.getTextLength()) { return false; } FindManager findManager = FindManager.getInstance(myProject); final CharSequence foundString = document.getCharsSequence().subSequence(textOffset, textEndOffset); PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(document); FindResult findResult = findManager.findString( document.getCharsSequence(), textOffset, findModel, file != null ? file.getVirtualFile() : null); if (!findResult.isStringFound()) { return false; } stringToReplace.set( FindManager.getInstance(myProject) .getStringToReplace(foundString.toString(), findModel, textOffset, document.getText())); return true; }
@Override public void actionPerformed(AnActionEvent event) { Presentation presentation = event.getPresentation(); DataContext dataContext = event.getDataContext(); Project project = CommonDataKeys.PROJECT.getData(dataContext); Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (project == null || editor == null) { presentation.setEnabled(false); return; } PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (file == null || file.getVirtualFile() == null) { presentation.setEnabled(false); return; } boolean hasSelection = editor.getSelectionModel().hasSelection(); LayoutCodeDialog dialog = new LayoutCodeDialog(project, file, hasSelection, HELP_ID); dialog.show(); if (dialog.isOK()) { new FileInEditorProcessor(file, editor, dialog.getRunOptions()).processCode(); } }
private CompletionInitializationContext runContributorsBeforeCompletion( Editor editor, PsiFile psiFile, int invocationCount, Caret caret) { final Ref<CompletionContributor> current = Ref.create(null); CompletionInitializationContext context = new CompletionInitializationContext( editor, caret, psiFile, myCompletionType, invocationCount) { CompletionContributor dummyIdentifierChanger; @Override public void setDummyIdentifier(@NotNull String dummyIdentifier) { super.setDummyIdentifier(dummyIdentifier); if (dummyIdentifierChanger != null) { LOG.error( "Changing the dummy identifier twice, already changed by " + dummyIdentifierChanger); } dummyIdentifierChanger = current.get(); } }; List<CompletionContributor> contributors = CompletionContributor.forLanguage(context.getPositionLanguage()); Project project = psiFile.getProject(); List<CompletionContributor> filteredContributors = DumbService.getInstance(project).filterByDumbAwareness(contributors); for (final CompletionContributor contributor : filteredContributors) { current.set(contributor); contributor.beforeCompletion(context); CompletionAssertions.checkEditorValid(editor); assert !PsiDocumentManager.getInstance(project).isUncommited(editor.getDocument()) : "Contributor " + contributor + " left the document uncommitted"; } return context; }
/** * Validates that content of the editor as well as caret and selection matches one specified in * data file that should be formed with the same format as one used in configureByFile * * @param message - this check specific message. Added to text, caret position, selection * checking. May be null * @param filePath - relative path from %IDEA_INSTALLATION_HOME%/testData/ * @param ignoreTrailingSpaces - whether trailing spaces in editor in data file should be stripped * prior to comparing. */ protected void checkResultByFile( @Nullable String message, @TestDataFile @NotNull String filePath, final boolean ignoreTrailingSpaces) { bringRealEditorBack(); getProject().getComponent(PostprocessReformattingAspect.class).doPostponedFormatting(); if (ignoreTrailingSpaces) { final Editor editor = myEditor; TrailingSpacesStripper.stripIfNotCurrentLine(editor.getDocument(), false); EditorUtil.fillVirtualSpaceUntilCaret(editor); } PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); String fullPath = getTestDataPath() + filePath; File ioFile = new File(fullPath); assertTrue(getMessage("Cannot find file " + fullPath, message), ioFile.exists()); String fileText = null; try { fileText = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8_CHARSET); } catch (IOException e) { LOG.error(e); } checkResultByText( message, StringUtil.convertLineSeparators(fileText), ignoreTrailingSpaces, getTestDataPath() + "/" + filePath); }
public boolean isAllAnalysisFinished(@NotNull PsiFile file) { if (myDisposed) return false; Document document = PsiDocumentManager.getInstance(myProject).getCachedDocument(file); return document != null && document.getModificationStamp() == file.getModificationStamp() && myFileStatusMap.allDirtyScopesAreNull(document); }
public boolean isErrorAnalyzingFinished(PsiFile file) { if (myDisposed) return false; Document document = PsiDocumentManager.getInstance(myProject).getCachedDocument(file); return document != null && document.getModificationStamp() == file.getModificationStamp() && myFileStatusMap.getFileDirtyScope(document, Pass.UPDATE_ALL) == null; }
void loadFromEditor(@NotNull Editor editor) { assertDispatchThread(); LOG.assertTrue(!editor.isDisposed()); clear(); PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject); documentManager.commitDocument(editor.getDocument()); PsiFile file = documentManager.getPsiFile(editor.getDocument()); SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(myProject); EditorFoldingInfo info = EditorFoldingInfo.get(editor); FoldRegion[] foldRegions = editor.getFoldingModel().getAllFoldRegions(); for (FoldRegion region : foldRegions) { if (!region.isValid()) continue; PsiElement element = info.getPsiElement(region); boolean expanded = region.isExpanded(); boolean collapseByDefault = element != null && FoldingPolicy.isCollapseByDefault(element) && !FoldingUtil.caretInsideRange(editor, TextRange.create(region)); if (collapseByDefault == expanded || element == null) { FoldingInfo fi = new FoldingInfo(region.getPlaceholderText(), expanded); if (element != null) { myPsiElements.add(smartPointerManager.createSmartPsiElementPointer(element, file)); element.putUserData(FOLDING_INFO_KEY, fi); } else if (region.isValid()) { myRangeMarkers.add(region); region.putUserData(FOLDING_INFO_KEY, fi); } } } }
private static LineRange expandLineRangeToCoverPsiElements( final LineRange range, Editor editor, final PsiFile file) { Pair<PsiElement, PsiElement> psiRange = getElementRange(editor, file, range); if (psiRange == null) return null; final PsiElement parent = PsiTreeUtil.findCommonParent(psiRange.getFirst(), psiRange.getSecond()); Pair<PsiElement, PsiElement> elementRange = getElementRange(parent, psiRange.getFirst(), psiRange.getSecond()); if (elementRange == null) return null; int endOffset = elementRange.getSecond().getTextRange().getEndOffset(); Document document = editor.getDocument(); if (endOffset > document.getTextLength()) { LOG.assertTrue(!PsiDocumentManager.getInstance(file.getProject()).isUncommited(document)); LOG.assertTrue(PsiDocumentManagerImpl.checkConsistency(file, document)); } int endLine; if (endOffset == document.getTextLength()) { endLine = document.getLineCount(); } else { endLine = editor.offsetToLogicalPosition(endOffset).line + 1; endLine = Math.min(endLine, document.getLineCount()); } int startLine = Math.min( range.startLine, editor.offsetToLogicalPosition(elementRange.getFirst().getTextOffset()).line); endLine = Math.max(endLine, range.endLine); return new LineRange(startLine, endLine); }
@Nullable private static PsiElement getSelectedPsiElement( final DataContext dataContext, final Project project) { PsiElement element = null; final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (editor != null) { final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile != null) { final int offset = editor.getCaretModel().getOffset(); element = psiFile.findElementAt(offset); if (element == null && offset > 0 && offset == psiFile.getTextLength()) { element = psiFile.findElementAt(offset - 1); } } } if (element == null) { final PsiElement[] elements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext); element = elements != null && elements.length > 0 ? elements[0] : null; } if (element == null) { final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext); if (files != null && files.length > 0) { element = PsiManager.getInstance(project).findFile(files[0]); } } return element; }
private void selectViewableElement() { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); final Object currentEditorElement = myTreeModel.getCurrentEditorElement(); if (currentEditorElement != null) { select(currentEditorElement, false); } }
public static void doActualPsiChange(@NotNull final PsiFile file, final DiffLog diffLog) { file.getViewProvider().beforeContentsSynchronized(); try { final Document document = file.getViewProvider().getDocument(); PsiDocumentManagerImpl documentManager = (PsiDocumentManagerImpl) PsiDocumentManager.getInstance(file.getProject()); PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = documentManager.getSynchronizer().getTransaction(document); final PsiFileImpl fileImpl = (PsiFileImpl) file; if (transaction == null) { final PomModel model = PomManager.getModel(fileImpl.getProject()); model.runTransaction( new PomTransactionBase(fileImpl, model.getModelAspect(TreeAspect.class)) { @Override public PomModelEvent runInner() { return new TreeAspectEvent(model, diffLog.performActualPsiChange(file)); } }); } else { diffLog.performActualPsiChange(file); } } catch (IncorrectOperationException e) { LOG.error(e); } }
private static void commit(@NotNull PsiFile file) { PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject()); Document document = manager.getDocument(file); if (document != null) { manager.commitDocument(document); } }
public static TextWithImports getEditorText(final Editor editor) { if (editor == null) { return null; } final Project project = editor.getProject(); if (project == null) return null; String defaultExpression = editor.getSelectionModel().getSelectedText(); if (defaultExpression == null) { int offset = editor.getCaretModel().getOffset(); PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile != null) { PsiElement elementAtCursor = psiFile.findElementAt(offset); if (elementAtCursor != null) { final EditorTextProvider textProvider = EditorTextProvider.EP.forLanguage(elementAtCursor.getLanguage()); if (textProvider != null) { final TextWithImports editorText = textProvider.getEditorText(elementAtCursor); if (editorText != null) return editorText; } } } } else { return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, defaultExpression); } return null; }
@NotNull private static Document setupFileEditorAndDocument( @NotNull String fileName, @NotNull String fileText) throws IOException { EncodingProjectManager.getInstance(getProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET); EncodingProjectManager.getInstance(ProjectManager.getInstance().getDefaultProject()) .setEncoding(null, CharsetToolkit.UTF8_CHARSET); PostprocessReformattingAspect.getInstance(ourProject).doPostponedFormatting(); deleteVFile(); myVFile = getSourceRoot().createChildData(null, fileName); VfsUtil.saveText(myVFile, fileText); final FileDocumentManager manager = FileDocumentManager.getInstance(); final Document document = manager.getDocument(myVFile); assertNotNull("Can't create document for '" + fileName + "'", document); manager.reloadFromDisk(document); document.insertString(0, " "); document.deleteString(0, 1); myFile = getPsiManager().findFile(myVFile); assertNotNull( "Can't create PsiFile for '" + fileName + "'. Unknown file type most probably.", myFile); assertTrue(myFile.isPhysical()); myEditor = createEditor(myVFile); myVFile.setCharset(CharsetToolkit.UTF8_CHARSET); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); return document; }
public void invoke( @NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) { PsiDocumentManager.getInstance(project).commitAllDocuments(); final LookupEx lookup = LookupManagerImpl.getActiveLookup(editor); if (lookup != null) { lookup.showElementActions(); return; } if (HintManagerImpl.getInstanceImpl().performCurrentQuestionAction()) return; // intentions check isWritable before modification: if (!file.isWritable()) return; if (file instanceof PsiCodeFragment) return; TemplateState state = TemplateManagerImpl.getTemplateState(editor); if (state != null && !state.isFinished()) { return; } final DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl) DaemonCodeAnalyzer.getInstance(project); codeAnalyzer.autoImportReferenceAtCursor(editor, file); // let autoimport complete ShowIntentionsPass.IntentionsInfo intentions = new ShowIntentionsPass.IntentionsInfo(); ShowIntentionsPass.getActionsToShow(editor, file, intentions, -1); if (!intentions.isEmpty()) { IntentionHintComponent.showIntentionHint(project, file, editor, intentions, true); } }
@Nullable @Override public TextRange getExpressionRangeAtOffset( final Project project, final Document document, final int offset, final boolean sideEffectsAllowed) { final Ref<TextRange> currentRange = Ref.create(null); PsiDocumentManager.getInstance(project) .commitAndRunReadAction( new Runnable() { @Override public void run() { try { PsiElement elementAtCursor = DebuggerUtilsEx.findElementAt( PsiDocumentManager.getInstance(project).getPsiFile(document), offset); if (elementAtCursor == null || !elementAtCursor.isValid()) { return; } Pair<PsiElement, TextRange> pair = findExpression(elementAtCursor, sideEffectsAllowed); if (pair != null) { currentRange.set(pair.getSecond()); } } catch (IndexNotReadyException ignored) { } } }); return currentRange.get(); }
public void testAddSourceRoot() throws Exception { File dir = createTempDirectory(); final VirtualFile root = LocalFileSystem.getInstance() .refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/')); new WriteCommandAction.Simple(getProject()) { @Override protected void run() throws Throwable { PsiTestUtil.addContentRoot(myModule, root); VirtualFile newFile = createChildData(root, "New.java"); setFileText(newFile, "class A{ Exception e;} //todo"); } }.execute().throwException(); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); PsiTodoSearchHelper.SERVICE .getInstance(myProject) .findFilesWithTodoItems(); // to initialize caches PsiTestUtil.addSourceRoot(myModule, root); PsiClass exceptionClass = myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject())); assertNotNull(exceptionClass); checkUsages(exceptionClass, new String[] {"1.java", "2.java", "New.java"}); checkTodos(new String[] {"2.java", "New.java"}); }
public void testSCR6066() throws Exception { ProjectRootManagerEx rootManager = (ProjectRootManagerEx) ProjectRootManager.getInstance(myProject); final VirtualFile root = rootManager.getContentRoots()[0]; PsiTodoSearchHelper.SERVICE .getInstance(myProject) .findFilesWithTodoItems(); // to initialize caches new WriteCommandAction.Simple(getProject()) { @Override protected void run() throws Throwable { VirtualFile newFile = createChildData(root, "New.java"); setFileText(newFile, "class A{ Exception e;} //todo"); } }.execute().throwException(); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches PsiTestUtil.addExcludedRoot(myModule, root); PsiClass exceptionClass = myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject())); assertNotNull(exceptionClass); checkUsages(exceptionClass, new String[] {}); checkTodos(new String[] {}); }
private void queueElement( @NotNull PsiElement child, final boolean whitespaceOptimizationAllowed, @NotNull PsiTreeChangeEvent event) { ApplicationManager.getApplication().assertIsDispatchThread(); PsiFile file = event.getFile(); if (file == null) file = child.getContainingFile(); if (file == null) { myFileStatusMap.markAllFilesDirty(child); return; } if (!child.isValid()) return; PsiDocumentManagerImpl pdm = (PsiDocumentManagerImpl) PsiDocumentManager.getInstance(myProject); Document document = pdm.getCachedDocument(file); if (document != null) { if (pdm.getSynchronizer().getTransaction(document) == null) { // content reload, language level change or some other big change myFileStatusMap.markAllFilesDirty(child); return; } List<Pair<PsiElement, Boolean>> toUpdate = changedElements.get(document); if (toUpdate == null) { toUpdate = new SmartList<>(); changedElements.put(document, toUpdate); } toUpdate.add(Pair.create(child, whitespaceOptimizationAllowed)); } }
public void testRemoveSourceRoot() { final VirtualFile root = ModuleRootManager.getInstance(myModule).getContentRoots()[0]; PsiTodoSearchHelper.SERVICE .getInstance(myProject) .findFilesWithTodoItems(); // to initialize caches new WriteCommandAction.Simple(getProject()) { @Override protected void run() throws Throwable { VirtualFile newFile = createChildData(root, "New.java"); setFileText(newFile, "class A{ Exception e;} //todo"); } }.execute().throwException(); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches VirtualFile[] sourceRoots = ModuleRootManager.getInstance(myModule).getSourceRoots(); LOG.assertTrue(sourceRoots.length == 1); PsiTestUtil.removeSourceRoot(myModule, sourceRoots[0]); PsiClass exceptionClass = myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject())); assertNotNull(exceptionClass); // currently it actually finds usages by FQN due to Java PSI enabled for out-of-source java // files // so the following check is disabled // checkUsages(exceptionClass, new String[]{}); checkTodos(new String[] {"2.java", "New.java"}); }