下面列出了com.intellij.psi.PsiFile#getTextLength ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public boolean isInContext(@NotNull PsiFile file, int offset) {
// offset is where cursor or insertion point is I guess
if ( !PsiUtilBase.getLanguageAtOffset(file, offset).isKindOf(ANTLRv4Language.INSTANCE) ) {
return false;
}
if ( offset==file.getTextLength() ) { // allow at EOF
offset--;
}
PsiElement element = file.findElementAt(offset);
// String trace = DebugUtil.currentStackTrace();
// System.out.println("isInContext: element " + element +", text="+element.getText());
// System.out.println(trace);
if ( element==null ) {
return false;
}
return isInContext(file, element, offset);
}
@NotNull
private TextRange getTokenRange(CommonToken ct, @NotNull PsiFile file) {
int startIndex = ct.getStartIndex();
int stopIndex = ct.getStopIndex();
if ( startIndex >= file.getTextLength() ) {
// can happen in case of a 'mismatched input EOF' error
startIndex = stopIndex = file.getTextLength() - 1;
}
if ( startIndex<0 ) {
// can happen on empty files, in that case we won't be able to show any error :/
startIndex = 0;
}
return new TextRange(startIndex, stopIndex + 1);
}
private void diagnoseLengthMismatch(VirtualFile vFile, boolean wasIndexedAlready, @Nullable Document document, boolean saved, @Nullable PsiFile cachedPsi) {
String message = "Outdated stub in index: " +
vFile +
" " +
getIndexingStampInfo(vFile) +
", doc=" +
document +
", docSaved=" +
saved +
", wasIndexedAlready=" +
wasIndexedAlready +
", queried at " +
vFile.getTimeStamp();
message += "\ndoc length=" + (document == null ? -1 : document.getTextLength()) + "\nfile length=" + vFile.getLength();
if (cachedPsi != null) {
message += "\ncached PSI " + cachedPsi.getClass();
if (cachedPsi instanceof PsiFileImpl && ((PsiFileImpl)cachedPsi).isContentsLoaded()) {
message += "\nPSI length=" + cachedPsi.getTextLength();
}
List<Project> projects = ContainerUtil.findAll(ProjectManager.getInstance().getOpenProjects(), p -> PsiManagerEx.getInstanceEx(p).getFileManager().findCachedViewProvider(vFile) != null);
message += "\nprojects with file: " + (LOG.isDebugEnabled() ? projects.toString() : projects.size());
}
processError(vFile, message, new Exception());
}
private static void validateModel(FormattingModel model) throws FormattingModelInconsistencyException {
FormattingDocumentModel documentModel = model.getDocumentModel();
Document document = documentModel.getDocument();
Block rootBlock = model.getRootBlock();
if (rootBlock instanceof ASTBlock) {
PsiElement rootElement = ((ASTBlock)rootBlock).getNode().getPsi();
if (!rootElement.isValid()) {
throw new FormattingModelInconsistencyException("Invalid root block PSI element");
}
PsiFile file = rootElement.getContainingFile();
Project project = file.getProject();
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
if (documentManager.isUncommited(document)) {
throw new FormattingModelInconsistencyException("Uncommitted document");
}
if (document.getTextLength() != file.getTextLength()) {
throw new FormattingModelInconsistencyException("Document length " + document.getTextLength() + " doesn't match PSI file length " + file.getTextLength() + ", language: " + file.getLanguage());
}
}
}
@Nullable
@RequiredUIAccess
private static PsiElement getSelectedPsiElement(final DataContext dataContext, final Project project) {
PsiElement element = null;
final Editor editor = dataContext.getData(CommonDataKeys.EDITOR);
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 = dataContext.getData(LangDataKeys.PSI_ELEMENT_ARRAY);
element = elements != null && elements.length > 0 ? elements[0] : null;
}
if (element == null) {
final VirtualFile[] files = dataContext.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY);
if (files != null && files.length > 0) {
element = PsiManager.getInstance(project).findFile(files[0]);
}
}
return element;
}
private static int getCurrentTextContentLength(Project project, VirtualFile vFile, Document document, PsiFile psiFile) {
if (vFile.getFileType().isBinary()) {
return -1;
}
if (psiFile instanceof PsiFileImpl && ((PsiFileImpl)psiFile).isContentsLoaded()) {
return psiFile.getTextLength();
}
if (document != null) {
return PsiDocumentManager.getInstance(project).getLastCommittedText(document).length();
}
return -1;
}
public FormattingProgressTask(@Nullable Project project, @Nonnull PsiFile file, @Nonnull Document document) {
super(project, getTitle(file));
myFile = new WeakReference<VirtualFile>(file.getVirtualFile());
myDocument = new WeakReference<Document>(document);
myFileTextLength = file.getTextLength();
addCallback(EventType.CANCEL, new MyCancelCallback());
}
static void assertCommitSuccessful(Editor editor, PsiFile psiFile) {
Document document = editor.getDocument();
int docLength = document.getTextLength();
int psiLength = psiFile.getTextLength();
PsiDocumentManager manager = PsiDocumentManager.getInstance(psiFile.getProject());
boolean committed = !manager.isUncommited(document);
if (docLength == psiLength && committed) {
return;
}
FileViewProvider viewProvider = psiFile.getViewProvider();
String message = "unsuccessful commit:";
message += "\nmatching=" + (psiFile == manager.getPsiFile(document));
message += "\ninjectedEditor=" + (editor instanceof EditorWindow);
message += "\ninjectedFile=" + InjectedLanguageManager.getInstance(psiFile.getProject()).isInjectedFragment(psiFile);
message += "\ncommitted=" + committed;
message += "\nfile=" + psiFile.getName();
message += "\nfile class=" + psiFile.getClass();
message += "\nfile.valid=" + psiFile.isValid();
message += "\nfile.physical=" + psiFile.isPhysical();
message += "\nfile.eventSystemEnabled=" + viewProvider.isEventSystemEnabled();
message += "\nlanguage=" + psiFile.getLanguage();
message += "\ndoc.length=" + docLength;
message += "\npsiFile.length=" + psiLength;
String fileText = psiFile.getText();
if (fileText != null) {
message += "\npsiFile.text.length=" + fileText.length();
}
FileASTNode node = psiFile.getNode();
if (node != null) {
message += "\nnode.length=" + node.getTextLength();
String nodeText = node.getText();
message += "\nnode.text.length=" + nodeText.length();
}
VirtualFile virtualFile = viewProvider.getVirtualFile();
message += "\nvirtualFile=" + virtualFile;
message += "\nvirtualFile.class=" + virtualFile.getClass();
message += "\n" + DebugUtil.currentStackTrace();
throw new RuntimeExceptionWithAttachments("Commit unsuccessful", message, new Attachment(virtualFile.getPath() + "_file.txt", StringUtil.notNullize(fileText)), createAstAttachment(psiFile, psiFile),
new Attachment("docText.txt", document.getText()));
}
static void assertHostInfo(PsiFile hostCopy, OffsetMap hostMap) {
PsiUtilCore.ensureValid(hostCopy);
if (hostMap.getOffset(CompletionInitializationContext.START_OFFSET) > hostCopy.getTextLength()) {
throw new AssertionError("startOffset outside the host file: " + hostMap.getOffset(CompletionInitializationContext.START_OFFSET) + "; " + hostCopy);
}
}
@Override
@Nullable
public TextEditorHighlightingPass createHighlightingPass(@Nonnull final PsiFile file, @Nonnull final Editor editor) {
final long psiModificationCount = PsiManager.getInstance(myProject).getModificationTracker().getModificationCount();
if (psiModificationCount == myPsiModificationCount) {
return null; //optimization
}
if (myFileToolsCache.containsKey(file) && !myFileToolsCache.get(file)) {
return null;
}
ProperTextRange visibleRange = VisibleHighlightingPassFactory.calculateVisibleRange(editor);
return new LocalInspectionsPass(file, editor.getDocument(), 0, file.getTextLength(), visibleRange, true, new DefaultHighlightInfoProcessor()) {
@Nonnull
@Override
List<LocalInspectionToolWrapper> getInspectionTools(@Nonnull InspectionProfileWrapper profile) {
List<LocalInspectionToolWrapper> tools = super.getInspectionTools(profile);
List<LocalInspectionToolWrapper> result = tools.stream().filter(LocalInspectionToolWrapper::runForWholeFile).collect(Collectors.toList());
myFileToolsCache.put(file, !result.isEmpty());
return result;
}
@Override
protected String getPresentableName() {
return DaemonBundle.message("pass.whole.inspections");
}
@Override
void inspectInjectedPsi(@Nonnull List<PsiElement> elements,
boolean onTheFly,
@Nonnull ProgressIndicator indicator,
@Nonnull InspectionManager iManager,
boolean inVisibleRange,
@Nonnull List<LocalInspectionToolWrapper> wrappers) {
// already inspected in LIP
}
@Override
protected void applyInformationWithProgress() {
super.applyInformationWithProgress();
myPsiModificationCount = PsiManager.getInstance(myProject).getModificationTracker().getModificationCount();
}
};
}
@Override
public TextEditorHighlightingPass createMainHighlightingPass(@Nonnull PsiFile file, @Nonnull Document document, @Nonnull HighlightInfoProcessor highlightInfoProcessor) {
// no applying to the editor - for read-only analysis only
return new GeneralHighlightingPass(file.getProject(), file, document, 0, file.getTextLength(), true, new ProperTextRange(0, document.getTextLength()), null, highlightInfoProcessor);
}
/**
* Checks that the {@param outline} matches the current version of {@param file}.
*
* <p>
* An outline and file match if they have the same length.
*/
private boolean isOutdated(@NotNull FlutterOutline outline, @NotNull PsiFile file) {
final DartAnalysisServerService das = DartAnalysisServerService.getInstance(file.getProject());
return file.getTextLength() != outline.getLength()
&& file.getTextLength() != das.getConvertedOffset(file.getVirtualFile(), outline.getLength());
}
/**
* Checks that the {@param outline} matches the current version of {@param file}.
*
* <p>
* An outline and file match if they have the same length.
*/
private boolean isOutdated(@NotNull FlutterOutline outline, @NotNull PsiFile file) {
final DartAnalysisServerService das = DartAnalysisServerService.getInstance(file.getProject());
return file.getTextLength() != outline.getLength()
&& file.getTextLength() != das.getConvertedOffset(file.getVirtualFile(), outline.getLength());
}