Java Code Examples for com.intellij.psi.PsiFile#getTextLength()

The following examples show how to use com.intellij.psi.PsiFile#getTextLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ANTLRLiveTemplateContext.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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);
	}
 
Example 2
Source File: ANTLRv4ExternalAnnotator.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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);
}
 
Example 3
Source File: StubTreeLoaderImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 4
Source File: FormatterImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
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());
    }
  }
}
 
Example 5
Source File: ConfigurationContext.java    From consulo with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 6
Source File: StubTreeLoaderImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: FormattingProgressTask.java    From consulo with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 8
Source File: CompletionAssertions.java    From consulo with Apache License 2.0 4 votes vote down vote up
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()));
}
 
Example 9
Source File: CompletionAssertions.java    From consulo with Apache License 2.0 4 votes vote down vote up
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);
  }
}
 
Example 10
Source File: WholeFileLocalInspectionsPassFactory.java    From consulo with Apache License 2.0 4 votes vote down vote up
@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();
    }
  };
}
 
Example 11
Source File: GeneralHighlightingPassFactory.java    From consulo with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 12
Source File: ActiveEditorsOutlineService.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * 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());
}
 
Example 13
Source File: ActiveEditorsOutlineService.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * 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());
}