private static void addDynamicAnnotation( HighlightInfo info, GrReferenceExpression referenceExpression, HighlightDisplayKey key) { final PsiFile containingFile = referenceExpression.getContainingFile(); if (containingFile != null) { VirtualFile file = containingFile.getVirtualFile(); if (file == null) return; } else { return; } if (isCall(referenceExpression)) { PsiType[] argumentTypes = PsiUtil.getArgumentTypes(referenceExpression, false); if (argumentTypes != null) { QuickFixAction.registerQuickFixAction( info, referenceExpression.getTextRange(), new DynamicMethodFix(referenceExpression, argumentTypes), key); } } else { QuickFixAction.registerQuickFixAction( info, referenceExpression.getTextRange(), new DynamicPropertyFix(referenceExpression), key); } }
private void highlightInjectedSyntax( @NotNull PsiFile injectedPsi, @NotNull HighlightInfoHolder holder) { List<Trinity<IElementType, SmartPsiElementPointer<PsiLanguageInjectionHost>, TextRange>> tokens = InjectedLanguageUtil.getHighlightTokens(injectedPsi); if (tokens == null) return; final Language injectedLanguage = injectedPsi.getLanguage(); Project project = injectedPsi.getProject(); SyntaxHighlighter syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter( injectedLanguage, project, injectedPsi.getVirtualFile()); final TextAttributes defaultAttrs = myGlobalScheme.getAttributes(HighlighterColors.TEXT); for (Trinity<IElementType, SmartPsiElementPointer<PsiLanguageInjectionHost>, TextRange> token : tokens) { ProgressManager.checkCanceled(); IElementType tokenType = token.getFirst(); PsiLanguageInjectionHost injectionHost = token.getSecond().getElement(); if (injectionHost == null) continue; TextRange textRange = token.getThird(); TextAttributesKey[] keys = syntaxHighlighter.getTokenHighlights(tokenType); if (textRange.getLength() == 0) continue; TextRange annRange = textRange.shiftRight(injectionHost.getTextRange().getStartOffset()); // force attribute colors to override host' ones TextAttributes attributes = null; for (TextAttributesKey key : keys) { TextAttributes attrs2 = myGlobalScheme.getAttributes(key); if (attrs2 != null) { attributes = attributes == null ? attrs2 : TextAttributes.merge(attributes, attrs2); } } TextAttributes forcedAttributes; if (attributes == null || attributes.isEmpty() || attributes.equals(defaultAttrs)) { forcedAttributes = TextAttributes.ERASE_MARKER; } else { HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT) .range(annRange) .textAttributes(TextAttributes.ERASE_MARKER) .createUnconditionally(); holder.add(info); forcedAttributes = new TextAttributes( attributes.getForegroundColor(), attributes.getBackgroundColor(), attributes.getEffectColor(), attributes.getEffectType(), attributes.getFontType()); } HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT) .range(annRange) .textAttributes(forcedAttributes) .createUnconditionally(); holder.add(info); } }
private void updateEditorText() { disposeNonTextEditor(); final PsiElement elt = myElements[myIndex].getNavigationElement(); Project project = elt.getProject(); PsiFile psiFile = getContainingFile(elt); final VirtualFile vFile = psiFile.getVirtualFile(); if (vFile == null) return; final FileEditorProvider[] providers = FileEditorProviderManager.getInstance().getProviders(project, vFile); for (FileEditorProvider provider : providers) { if (provider instanceof TextEditorProvider) { updateTextElement(elt); myBinarySwitch.show(myViewingPanel, TEXT_PAGE_KEY); break; } else if (provider.accept(project, vFile)) { myCurrentNonTextEditorProvider = provider; myNonTextEditor = myCurrentNonTextEditorProvider.createEditor(project, vFile); myBinaryPanel.removeAll(); myBinaryPanel.add(myNonTextEditor.getComponent()); myBinarySwitch.show(myViewingPanel, BINARY_PAGE_KEY); break; } } }
/** * @return true, if the element contains a reference to a different class than fullyQualifiedName * but which has the same class name */ public static boolean containsConflictingReference(PsiFile element, String fullyQualifiedName) { final Map<String, Boolean> cachedValue = CachedValuesManager.getManager(element.getProject()) .getCachedValue( element, new CachedValueProvider<Map<String, Boolean>>() { @Nullable @Override public Result<Map<String, Boolean>> compute() { return new Result<Map<String, Boolean>>( Collections.synchronizedMap(new HashMap<String, Boolean>()), PsiModificationTracker.MODIFICATION_COUNT); } }); Boolean conflictingRef = cachedValue.get(fullyQualifiedName); if (conflictingRef != null) { return conflictingRef.booleanValue(); } final ConflictingClassReferenceVisitor visitor = new ConflictingClassReferenceVisitor(fullyQualifiedName); element.accept(visitor); conflictingRef = visitor.isConflictingReferenceFound(); cachedValue.put(fullyQualifiedName, conflictingRef); return conflictingRef.booleanValue(); }
public AddModuleDependencyFix( Module currentModule, VirtualFile classVFile, PsiClass[] classes, PsiReference reference) { final PsiElement psiElement = reference.getElement(); final Project project = psiElement.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (PsiClass aClass : classes) { if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue; PsiFile psiFile = aClass.getContainingFile(); if (psiFile == null) continue; VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile == null) continue; final Module classModule = fileIndex.getModuleForFile(virtualFile); if (classModule != null && classModule != currentModule && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) { myModules.add(classModule); } } myCurrentModule = currentModule; myClassVFile = classVFile; myClasses = classes; myReference = reference; }
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; }
@Override public boolean isInProject(@NotNull PsiElement element) { PsiFile file = element.getContainingFile(); if (file != null && file.isPhysical() && file.getViewProvider().getVirtualFile() instanceof LightVirtualFile) return true; if (element instanceof PsiDirectoryContainer) { PsiDirectory[] dirs = ((PsiDirectoryContainer) element).getDirectories(); for (PsiDirectory dir : dirs) { if (!isInProject(dir)) return false; } return true; } VirtualFile virtualFile = null; if (file != null) { virtualFile = file.getViewProvider().getVirtualFile(); } else if (element instanceof PsiFileSystemItem) { virtualFile = ((PsiFileSystemItem) element).getVirtualFile(); } if (virtualFile != null) { return myExcludedFileIndex.isInContent(virtualFile); } return false; }
@NotNull public static Collection<PsiFileSystemItem> getAbsoluteTopLevelDirLocations( final @NotNull PsiFile file) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) { return Collections.emptyList(); } final Project project = file.getProject(); PsiDirectory parent = file.getParent(); final Module module = ModuleUtil.findModuleForPsiElement(parent == null ? file : parent); if (module == null) { return Collections.emptyList(); } final FileReferenceHelper[] helpers = FileReferenceHelperRegistrar.getHelpers(); final ArrayList<PsiFileSystemItem> list = new ArrayList<PsiFileSystemItem>(); for (FileReferenceHelper helper : helpers) { if (helper.isMine(project, virtualFile)) { final Collection<PsiFileSystemItem> roots = helper.getRoots(module); for (PsiFileSystemItem root : roots) { LOG.assertTrue(root != null, "Helper " + helper + " produced a null root for " + file); } list.addAll(roots); } } if (list.size() == 0) { list.addAll(FileReferenceHelperRegistrar.getNotNullHelper(file).getRoots(module)); } return list; }
public static void clearCaches( @NotNull PsiFile injected, @NotNull DocumentWindowImpl documentWindow) { VirtualFileWindowImpl virtualFile = (VirtualFileWindowImpl) injected.getVirtualFile(); PsiManagerEx psiManagerEx = (PsiManagerEx) injected.getManager(); if (psiManagerEx.getProject().isDisposed()) return; psiManagerEx.getFileManager().setViewProvider(virtualFile, null); PsiElement context = InjectedLanguageManager.getInstance(injected.getProject()).getInjectionHost(injected); PsiFile hostFile; if (context != null) { hostFile = context.getContainingFile(); } else { VirtualFile delegate = virtualFile.getDelegate(); hostFile = delegate.isValid() ? psiManagerEx.findFile(delegate) : null; } if (hostFile != null) { // modification of cachedInjectedDocuments must be under PsiLock synchronized (PsiLock.LOCK) { List<DocumentWindow> cachedInjectedDocuments = getCachedInjectedDocuments(hostFile); for (int i = cachedInjectedDocuments.size() - 1; i >= 0; i--) { DocumentWindow cachedInjectedDocument = cachedInjectedDocuments.get(i); if (cachedInjectedDocument == documentWindow) { cachedInjectedDocuments.remove(i); } } } } }
@NotNull private MostlySingularMultiMap<String, AnnotationData> getDataFromFile( @NotNull final PsiFile file) { Pair<MostlySingularMultiMap<String, AnnotationData>, Long> cached = annotationFileToDataAndModStamp.get(file); final long fileModificationStamp = file.getModificationStamp(); if (cached != null && cached.getSecond() == fileModificationStamp) { return cached.getFirst(); } DataParsingSaxHandler handler = new DataParsingSaxHandler(file); try { SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); saxParser.parse(new InputSource(new StringReader(escapeAttributes(file.getText()))), handler); } catch (IOException e) { LOG.error(e); } catch (ParserConfigurationException e) { LOG.error(e); } catch (SAXException e) { LOG.error(e); } Pair<MostlySingularMultiMap<String, AnnotationData>, Long> pair = Pair.create(handler.getResult(), file.getModificationStamp()); annotationFileToDataAndModStamp.put(file, pair); return pair.first; }
@NotNull private List<AnnotationData> doCollect( @NotNull PsiModifierListOwner listOwner, boolean onlyWritable) { final List<PsiFile> files = findExternalAnnotationsFiles(listOwner); if (files == null) { return NO_DATA; } SmartList<AnnotationData> result = new SmartList<AnnotationData>(); String externalName = getExternalName(listOwner, false); if (externalName == null) return NO_DATA; for (PsiFile file : files) { if (!file.isValid()) continue; if (onlyWritable && !file.isWritable()) continue; MostlySingularMultiMap<String, AnnotationData> fileData = getDataFromFile(file); ContainerUtil.addAll(result, fileData.get(externalName)); } if (result.isEmpty()) { return NO_DATA; } result.trimToSize(); return result; }
@NotNull @Override public PsiPolyVariantReference getReference(PyResolveContext context) { final PsiFile file = getContainingFile(); final PyExpression qualifier = getQualifier(); // Handle import reference final PsiElement importParent = PsiTreeUtil.getParentOfType(this, PyImportElement.class, PyFromImportStatement.class); if (importParent != null) { return PyImportReference.forElement(this, importParent, context); } // Return special reference final ConsoleCommunication communication = file.getCopyableUserData(PydevConsoleRunner.CONSOLE_KEY); if (communication != null) { if (qualifier != null) { return new PydevConsoleReference(this, communication, qualifier.getText() + "."); } return new PydevConsoleReference(this, communication, ""); } if (qualifier != null) { return new PyQualifiedReference(this, context); } return new PyReferenceImpl(this, context); }
public static void addImportForItem(InsertionContext context, PsiClass aClass) { if (aClass.getQualifiedName() == null) return; PsiFile file = context.getFile(); int startOffset = context.getStartOffset(); int tail = context.getTailOffset(); int newTail = JavaCompletionUtil.insertClassReference(aClass, file, startOffset, tail); if (newTail > context.getDocument().getTextLength() || newTail < 0) { LOG.error( LogMessageEx.createEvent( "Invalid offset after insertion ", "offset=" + newTail + "\n" + "start=" + startOffset + "\n" + "tail=" + tail + "\n" + "file.length=" + file.getTextLength() + "\n" + "document=" + context.getDocument() + "\n" + DebugUtil.currentStackTrace(), AttachmentFactory.createAttachment(context.getDocument()))); return; } context.setTailOffset(newTail); JavaCompletionUtil.shortenReference(file, context.getStartOffset()); PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(); }
private static RefCountHolder getInstance( @NotNull PsiFile file, @NotNull ProgressIndicator indicator, boolean acquire) { HolderReference ref = file.getUserData(REF_COUNT_HOLDER_IN_FILE_KEY); RefCountHolder holder = com.intellij.reference.SoftReference.dereference(ref); if (holder == null && acquire) { holder = new RefCountHolder(file); HolderReference newRef = new HolderReference(holder); while (true) { boolean replaced = ((UserDataHolderEx) file).replace(REF_COUNT_HOLDER_IN_FILE_KEY, ref, newRef); if (replaced) { ref = newRef; break; } ref = file.getUserData(REF_COUNT_HOLDER_IN_FILE_KEY); RefCountHolder newHolder = com.intellij.reference.SoftReference.dereference(ref); if (newHolder != null) { holder = newHolder; break; } } } if (ref != null) { if (acquire) { ref.acquire(indicator); } else { ref.release(indicator); } } return holder; }
public boolean commitTransaction(final Document document) { ApplicationManager.getApplication().assertIsDispatchThread(); final DocumentChangeTransaction documentChangeTransaction = removeTransaction(document); if (documentChangeTransaction == null) return false; final PsiFile changeScope = documentChangeTransaction.myChangeScope; try { mySyncDocument = document; final PsiTreeChangeEventImpl fakeEvent = new PsiTreeChangeEventImpl(changeScope.getManager()); fakeEvent.setParent(changeScope); fakeEvent.setFile(changeScope); checkPsiModificationAllowed(fakeEvent); doSync( fakeEvent, true, new DocSyncAction() { @Override public void syncDocument( @NotNull Document document, @NotNull PsiTreeChangeEventImpl event) { doCommitTransaction(document, documentChangeTransaction); } }); myBus .syncPublisher(PsiDocumentTransactionListener.TOPIC) .transactionCompleted(document, changeScope); } catch (Throwable e) { myPsiDocumentManager.forceReload( changeScope.getViewProvider().getVirtualFile(), changeScope.getViewProvider()); ExceptionUtil.rethrowAllAsUnchecked(e); } finally { mySyncDocument = null; } return true; }
public static String getUnescapedText( PsiFile file, @Nullable final PsiElement startElement, @Nullable final PsiElement endElement) { final InjectedLanguageManager manager = InjectedLanguageManager.getInstance(file.getProject()); if (manager.getInjectionHost(file) == null) { return file.getText() .substring( startElement == null ? 0 : startElement.getTextRange().getStartOffset(), endElement == null ? file.getTextLength() : endElement.getTextRange().getStartOffset()); } final StringBuilder sb = new StringBuilder(); file.accept( new PsiRecursiveElementWalkingVisitor() { Boolean myState = startElement == null ? Boolean.TRUE : null; @Override public void visitElement(PsiElement element) { if (element == startElement) myState = Boolean.TRUE; if (element == endElement) myState = Boolean.FALSE; if (Boolean.FALSE == myState) return; if (Boolean.TRUE == myState && element.getFirstChild() == null) { sb.append(getUnescapedLeafText(element, false)); } else { super.visitElement(element); } } }); return sb.toString(); }
protected void moveCaretInsideBracesIfAny( @NotNull final Editor editor, @NotNull final PsiFile file) throws IncorrectOperationException { int caretOffset = editor.getCaretModel().getOffset(); final CharSequence chars = editor.getDocument().getCharsSequence(); if (CharArrayUtil.regionMatches(chars, caretOffset, "{}")) { caretOffset += 2; } else if (CharArrayUtil.regionMatches(chars, caretOffset, "{\n}")) { caretOffset += 3; } caretOffset = CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t") + 1; if (CharArrayUtil.regionMatches(chars, caretOffset - "{}".length(), "{}") || CharArrayUtil.regionMatches(chars, caretOffset - "{\n}".length(), "{\n}")) { commit(editor); final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(file.getProject()); final boolean old = settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE; settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false; PsiElement elt = PsiTreeUtil.getParentOfType(file.findElementAt(caretOffset - 1), PsiCodeBlock.class); reformat(elt); settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = old; editor.getCaretModel().moveToOffset(caretOffset - 1); } }
@Override public void navigate(Project project) { VirtualFile currentVirtualFile = null; AccessToken accessToken = ReadAction.start(); try { if (!myVirtualFile.isValid()) return; PsiFile psiFile = PsiManager.getInstance(project).findFile(myVirtualFile); if (psiFile != null) { PsiElement navigationElement = psiFile.getNavigationElement(); // Sources may be downloaded. if (navigationElement instanceof PsiFile) { currentVirtualFile = ((PsiFile) navigationElement).getVirtualFile(); } } if (currentVirtualFile == null) { currentVirtualFile = myVirtualFile; } } finally { accessToken.finish(); } new OpenFileHyperlinkInfo(myProject, currentVirtualFile, myLineNumber - 1).navigate(project); }
public static boolean isValidName( final Project project, final PsiElement psiElement, final String newName) { if (newName == null || newName.length() == 0) { return false; } final Condition<String> inputValidator = RenameInputValidatorRegistry.getInputValidator(psiElement); if (inputValidator != null) { return inputValidator.value(newName); } if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) { return newName.indexOf('\\') < 0 && newName.indexOf('/') < 0; } if (psiElement instanceof PomTargetPsiElement) { return !StringUtil.isEmptyOrSpaces(newName); } final PsiFile file = psiElement.getContainingFile(); final Language elementLanguage = psiElement.getLanguage(); final Language fileLanguage = file == null ? null : file.getLanguage(); Language language = fileLanguage == null ? elementLanguage : fileLanguage.isKindOf(elementLanguage) ? fileLanguage : elementLanguage; return LanguageNamesValidation.INSTANCE .forLanguage(language) .isIdentifier(newName.trim(), project); }
@NotNull public static <T extends PsiJavaCodeReferenceElement> JavaResolveResult[] multiResolveImpl( @NotNull T element, boolean incompleteCode, @NotNull ResolveCache.PolyVariantContextResolver<? super T> resolver) { FileASTNode fileElement = SharedImplUtil.findFileElement(element.getNode()); if (fileElement == null) { PsiUtilCore.ensureValid(element); LOG.error("fileElement == null!"); return JavaResolveResult.EMPTY_ARRAY; } PsiFile psiFile = SharedImplUtil.getContainingFile(fileElement); PsiManager manager = psiFile == null ? null : psiFile.getManager(); if (manager == null) { PsiUtilCore.ensureValid(element); LOG.error("getManager() == null!"); return JavaResolveResult.EMPTY_ARRAY; } boolean valid = psiFile.isValid(); if (!valid) { PsiUtilCore.ensureValid(element); LOG.error("psiFile.isValid() == false!"); return JavaResolveResult.EMPTY_ARRAY; } if (element instanceof PsiMethodReferenceExpression) { // method refs: do not cache results during parent conflict resolving, acceptable checks, etc final Map<PsiElement, PsiType> map = LambdaUtil.ourFunctionTypes.get(); if (map != null && map.containsKey(element)) { return (JavaResolveResult[]) resolver.resolve(element, psiFile, incompleteCode); } } return multiResolveImpl(manager.getProject(), psiFile, element, incompleteCode, resolver); }
@NotNull private static String[] collectNamesToImport( @NotNull PsiJavaFile file, @NotNull Set<String> namesToImportStaticly) { Set<String> names = new THashSet<String>(); final JspFile jspFile = JspPsiUtil.getJspFile(file); collectNamesToImport(names, file, namesToImportStaticly, jspFile); if (jspFile != null) { PsiFile[] files = ArrayUtil.mergeArrays( JspSpiUtil.getIncludingFiles(jspFile), JspSpiUtil.getIncludedFiles(jspFile), PsiFile.class); for (PsiFile includingFile : files) { final PsiFile javaRoot = includingFile.getViewProvider().getPsi(StdLanguages.JAVA); if (javaRoot instanceof PsiJavaFile && file != javaRoot) { collectNamesToImport(names, (PsiJavaFile) javaRoot, namesToImportStaticly, jspFile); } } } addUnresolvedImportNames(names, file, namesToImportStaticly); return ArrayUtil.toStringArray(names); }
public static void initOffsets(final PsiFile file, final OffsetMap offsetMap) { int offset = Math.max( offsetMap.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET), offsetMap.getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET)); PsiElement element = file.findElementAt(offset); if (element instanceof PsiWhiteSpace && (!element.textContains('\n') || CodeStyleSettingsManager.getSettings(file.getProject()) .getCommonSettings(JavaLanguage.INSTANCE) .METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE)) { element = file.findElementAt(element.getTextRange().getEndOffset()); } if (element == null) return; if (LEFT_PAREN.accepts(element)) { offsetMap.addOffset(LPAREN_OFFSET, element.getTextRange().getStartOffset()); PsiElement list = element.getParent(); PsiElement last = list.getLastChild(); if (last instanceof PsiJavaToken && ((PsiJavaToken) last).getTokenType() == JavaTokenType.RPARENTH) { offsetMap.addOffset(RPAREN_OFFSET, last.getTextRange().getStartOffset()); } offsetMap.addOffset(ARG_LIST_END_OFFSET, list.getTextRange().getEndOffset()); } }
private static void logStats(Collection<PsiFile> otherFiles, long start) { long time = System.currentTimeMillis() - start; final Multiset<String> stats = HashMultiset.create(); for (PsiFile file : otherFiles) { stats.add( StringUtil.notNullize(file.getViewProvider().getVirtualFile().getExtension()) .toLowerCase()); } List<String> extensions = ContainerUtil.newArrayList(stats.elementSet()); Collections.sort( extensions, new Comparator<String>() { @Override public int compare(String o1, String o2) { return stats.count(o2) - stats.count(o1); } }); String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" + "Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" + "Most frequent non-indexed file extensions: "; for (int i = 0; i < Math.min(10, extensions.size()); i++) { String extension = extensions.get(i); message += extension + "(" + stats.count(extension) + ") "; } LOG.info(message); }
@NotNull protected PsiElement[] doCreate(String newName, PsiDirectory directory) { PsiFile file = SilverStripeTemplatesFactory.createFromTemplate(directory, newName, selectedText); PsiElement child = file.getLastChild(); return child != null ? new PsiElement[] {file, child} : new PsiElement[] {file}; }
private void checkPsiIsCorrect(final FileViewProvider key) { PsiFile actualPsi = key.getPsi(key.getBaseLanguage()); PsiTreeDebugBuilder treeDebugBuilder = new PsiTreeDebugBuilder().setShowErrorElements(false).setShowWhiteSpaces(false); String actualPsiTree = treeDebugBuilder.psiToString(actualPsi); String fileName = key.getVirtualFile().getName(); PsiFile psi = PsiFileFactory.getInstance(myProject) .createFileFromText( fileName, FileTypeManager.getInstance().getFileTypeByFileName(fileName), actualPsi.getNode().getText(), LocalTimeCounter.currentTime(), false); if (actualPsi.getClass().equals(psi.getClass())) { String expectedPsi = treeDebugBuilder.psiToString(psi); if (!expectedPsi.equals(actualPsiTree)) { myReformatElements.clear(); assert expectedPsi.equals(actualPsiTree) : "Refactored psi should be the same as result of parsing"; } } }
public void update(final AnActionEvent event) { super.update(event); final Presentation presentation = event.getPresentation(); final DataContext context = event.getDataContext(); Module module = (Module) context.getData(LangDataKeys.MODULE.getName()); PsiFile currentFile = (PsiFile) context.getData(LangDataKeys.PSI_FILE.getName()); Editor editor = (Editor) context.getData(PlatformDataKeys.EDITOR.getName()); // VirtualFile currentFile = (VirtualFile) // context.getData(PlatformDataKeys.VIRTUAL_FILE.getName()); if (currentFile != null && editor != null) { boolean isSSFile = currentFile .getFileType() .getDefaultExtension() .equals(SilverStripeFileType.DEFAULT_EXTENSION); SelectionModel selectionModel = editor.getSelectionModel(); String selectedText = selectionModel.getSelectedText(); this.selectedText = selectedText; this.selectonModel = selectionModel; this.editor = editor; this.currentFile = currentFile; if (selectedText == null) { presentation.setEnabled(false); } if (!isSSFile) { presentation.setEnabled(false); presentation.setVisible(false); } } else { presentation.setEnabled(false); presentation.setVisible(false); } }
private static void checkResult( String[] fileNames, final ArrayList<PsiFile> filesList, int[] starts, final IntArrayList startsList, int[] ends, final IntArrayList endsList) { List<SearchResult> expected = new ArrayList<SearchResult>(); for (int i = 0; i < fileNames.length; i++) { String fileName = fileNames[i]; expected.add( new SearchResult( fileName, i < starts.length ? starts[i] : -1, i < ends.length ? ends[i] : -1)); } List<SearchResult> actual = new ArrayList<SearchResult>(); for (int i = 0; i < filesList.size(); i++) { PsiFile psiFile = filesList.get(i); actual.add( new SearchResult( psiFile.getName(), i < starts.length ? startsList.get(i) : -1, i < ends.length ? endsList.get(i) : -1)); } Collections.sort(expected); Collections.sort(actual); assertEquals("Usages don't match", expected, actual); }
private void doSync( @NotNull final PsiTreeChangeEvent event, boolean force, @NotNull final DocSyncAction syncAction) { if (!toProcessPsiEvent()) return; final PsiFile psiFile = event.getFile(); if (!(psiFile instanceof PsiFileEx) || !((PsiFileEx) psiFile).isContentsLoaded()) return; final DocumentEx document = getCachedDocument(psiFile, force); if (document == null) return; performAtomically( psiFile, new Runnable() { @Override public void run() { syncAction.syncDocument(document, (PsiTreeChangeEventImpl) event); } }); final boolean insideTransaction = myTransactionsMap.containsKey(document); if (!insideTransaction) { document.setModificationStamp(psiFile.getViewProvider().getModificationStamp()); } }
private static void reportInconsistentLength( PsiFile file, CharSequence newFileText, ASTNode node, int start, int end) { String message = "Index out of bounds: type=" + node.getElementType() + "; file=" + file + "; file.class=" + file.getClass() + "; start=" + start + "; end=" + end + "; length=" + node.getTextLength(); String newTextBefore = newFileText.subSequence(0, start).toString(); String oldTextBefore = file.getText().subSequence(0, start).toString(); if (oldTextBefore.equals(newTextBefore)) { message += "; oldTextBefore==newTextBefore"; } LOG.error( message, new Attachment(file.getName() + "_oldNodeText.txt", node.getText()), new Attachment(file.getName() + "_oldFileText.txt", file.getText()), new Attachment(file.getName() + "_newFileText.txt", newFileText.toString())); }
private static boolean navigateInCurrentEditor( @NotNull PsiElement element, @NotNull PsiFile currentFile, @NotNull Editor currentEditor) { if (element.getContainingFile() == currentFile) { int offset = element.getTextOffset(); PsiElement leaf = currentFile.findElementAt(offset); // check that element is really physically inside the file // there are fake elements with custom navigation (e.g. opening URL in browser) that override // getContainingFile for various reasons if (leaf != null && PsiTreeUtil.isAncestor(element, leaf, false)) { Project project = element.getProject(); CommandProcessor.getInstance() .executeCommand( project, () -> { IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); new OpenFileDescriptor( project, currentFile.getViewProvider().getVirtualFile(), offset) .navigateIn(currentEditor); }, "", null); return true; } } return false; }