Java Code Examples for com.intellij.psi.PsiDocumentManager#getPsiFile()

The following examples show how to use com.intellij.psi.PsiDocumentManager#getPsiFile() . 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: PasteReferenceProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void insert(final String fqn, final PsiElement element, final Editor editor, final QualifiedNameProvider provider) {
  final Project project = editor.getProject();
  if (project == null) return;

  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  documentManager.commitDocument(editor.getDocument());

  final PsiFile file = documentManager.getPsiFile(editor.getDocument());
  if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

  CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    Document document = editor.getDocument();
    documentManager.doPostponedOperationsAndUnblockDocument(document);
    documentManager.commitDocument(document);
    EditorModificationUtil.deleteSelectedText(editor);
    provider.insertQualifiedName(fqn, element, editor, project);
  }), IdeBundle.message("command.pasting.reference"), null);
}
 
Example 2
Source File: JavaImportsUtil.java    From KodeBeagle with Apache License 2.0 6 votes vote down vote up
public final Map<String, Set<String>> getImportInLines(final Editor projectEditor,
                                                       final Pair<Integer, Integer> pair) {
    PsiDocumentManager psiInstance =
            PsiDocumentManager.getInstance(windowObjects.getProject());
    PsiJavaFile psiJavaFile =
            (PsiJavaFile) psiInstance.getPsiFile(projectEditor.getDocument());
    PsiJavaElementVisitor psiJavaElementVisitor =
            new PsiJavaElementVisitor(pair.getFirst(), pair.getSecond());
    Map<String, Set<String>> finalImports = new HashMap<>();
    if (psiJavaFile != null && psiJavaFile.findElementAt(pair.getFirst()) != null) {
        PsiElement psiElement = psiJavaFile.findElementAt(pair.getFirst());
        final PsiElement psiMethod = PsiTreeUtil.getParentOfType(psiElement, PsiMethod.class);
        if (psiMethod != null) {
            psiMethod.accept(psiJavaElementVisitor);
        } else {
            final PsiClass psiClass = PsiTreeUtil.getParentOfType(psiElement, PsiClass.class);
            if (psiClass != null) {
                psiClass.accept(psiJavaElementVisitor);
            }
        }
        Map<String, Set<String>> importVsMethods = psiJavaElementVisitor.getImportVsMethods();
        finalImports = getImportsAndMethodsAfterValidation(psiJavaFile, importVsMethods);
    }
    return removeImplicitImports(finalImports);
}
 
Example 3
Source File: GotoCustomRegionAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@RequiredReadAction
private static Collection<FoldingDescriptor> getCustomFoldingDescriptors(@Nonnull Editor editor, @Nonnull Project project) {
  Set<FoldingDescriptor> foldingDescriptors = new HashSet<>();
  final Document document = editor.getDocument();
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  PsiFile file = documentManager != null ? documentManager.getPsiFile(document) : null;
  if (file != null) {
    final FileViewProvider viewProvider = file.getViewProvider();
    for (final Language language : viewProvider.getLanguages()) {
      final PsiFile psi = viewProvider.getPsi(language);
      final FoldingBuilder foldingBuilder = LanguageFolding.INSTANCE.forLanguage(language);
      if (psi != null) {
        for (FoldingDescriptor descriptor : LanguageFolding.buildFoldingDescriptors(foldingBuilder, psi, document, false)) {
          CustomFoldingBuilder customFoldingBuilder = getCustomFoldingBuilder(foldingBuilder, descriptor);
          if (customFoldingBuilder != null) {
            if (customFoldingBuilder.isCustomRegionStart(descriptor.getElement())) {
              foldingDescriptors.add(descriptor);
            }
          }
        }
      }
    }
  }
  return foldingDescriptors;
}
 
Example 4
Source File: GotoCustomRegionDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredReadAction
private Collection<FoldingDescriptor> getCustomFoldingDescriptors() {
  Set<FoldingDescriptor> foldingDescriptors = new HashSet<FoldingDescriptor>();
  final Document document = myEditor.getDocument();
  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
  PsiFile file = documentManager != null ? documentManager.getPsiFile(document) : null;
  if (file != null) {
    final FileViewProvider viewProvider = file.getViewProvider();
    for (final Language language : viewProvider.getLanguages()) {
      final PsiFile psi = viewProvider.getPsi(language);
      final FoldingBuilder foldingBuilder = LanguageFolding.INSTANCE.forLanguage(language);
      if (psi != null) {
        for (FoldingDescriptor descriptor : LanguageFolding.buildFoldingDescriptors(foldingBuilder, psi, document, false)) {
          CustomFoldingBuilder customFoldingBuilder = getCustomFoldingBuilder(foldingBuilder, descriptor);
          if (customFoldingBuilder != null) {
            if (customFoldingBuilder.isCustomRegionStart(descriptor.getElement())) {
              foldingDescriptors.add(descriptor);
            }
          }
        }
      }
    }
  }
  return foldingDescriptors;
}
 
Example 5
Source File: FileContentImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * @deprecated use {@link FileContent#getPsiFile()}
 */
@SuppressWarnings("DeprecatedIsStillUsed")
@Deprecated
@Nonnull
public PsiFile getPsiFileForPsiDependentIndex() {
  PsiFile psi = null;
  if (!myPhysicalContent) {
    Document document = FileDocumentManager.getInstance().getCachedDocument(getFile());

    if (document != null) {
      PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(getProject());
      if (psiDocumentManager.isUncommited(document)) {
        PsiFile existingPsi = psiDocumentManager.getPsiFile(document);
        if (existingPsi != null) {
          psi = existingPsi;
        }
      }
    }
  }
  if (psi == null) {
    psi = getFileFromText();
  }
  return psi;
}
 
Example 6
Source File: PasteHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
static void indentBlock(Project project, Editor editor, final int startOffset, final int endOffset, int originalCaretCol) {
  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  documentManager.commitAllDocuments();
  final Document document = editor.getDocument();
  PsiFile file = documentManager.getPsiFile(document);
  if (file == null) {
    return;
  }

  if (LanguageFormatting.INSTANCE.forContext(file) != null) {
    indentBlockWithFormatter(project, document, startOffset, endOffset, file);
  }
  else {
    indentPlainTextBlock(document, startOffset, endOffset, originalCaretCol);
  }
}
 
Example 7
Source File: RefreshActionBase.java    From KodeBeagle with Apache License 2.0 5 votes vote down vote up
protected final boolean checkFileType(final Document document, final String... fileExtensions) {
    List<String> extensions = Arrays.asList(fileExtensions);
    PsiDocumentManager psiInstance =
            PsiDocumentManager.getInstance(windowObjects.getProject());
    if (psiInstance != null && (psiInstance.getPsiFile(document)) != null) {
        PsiFile psiFile = psiInstance.getPsiFile(document);
        return psiFile != null
                && extensions.contains(psiFile.getFileType().getDefaultExtension());
    }
    return false;
}
 
Example 8
Source File: RearrangeCodeAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  final Project project = e.getProject();
  if (project == null) {
    return;
  }

  final Editor editor = e.getData(CommonDataKeys.EDITOR);
  if (editor == null) {
    return;
  }

  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  Document document = editor.getDocument();
  documentManager.commitDocument(document);

  final PsiFile file = documentManager.getPsiFile(document);
  if (file == null) {
    return;
  }

  SelectionModel model = editor.getSelectionModel();
  if (model.hasSelection()) {
    new RearrangeCodeProcessor(file, model).run();
  }
  else {
    new RearrangeCodeProcessor(file).run();
  }
}
 
Example 9
Source File: AutoPopupControllerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void autoPopupParameterInfo(@Nonnull final Editor editor, @Nullable final Object highlightedMethod) {
  if (DumbService.isDumb(myProject)) return;
  if (PowerSaveMode.isEnabled()) return;

  ApplicationManager.getApplication().assertIsDispatchThread();
  final CodeInsightSettings settings = CodeInsightSettings.getInstance();
  if (settings.AUTO_POPUP_PARAMETER_INFO) {
    final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
    PsiFile file = documentManager.getPsiFile(editor.getDocument());
    if (file == null) return;

    if (!documentManager.isUncommited(editor.getDocument())) {
      file = documentManager.getPsiFile(InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, file).getDocument());
      if (file == null) return;
    }

    Runnable request = () -> {
      if (!myProject.isDisposed() && !DumbService.isDumb(myProject) && !editor.isDisposed() && (EditorActivityManager.getInstance().isVisible(editor))) {
        int lbraceOffset = editor.getCaretModel().getOffset() - 1;
        try {
          PsiFile file1 = PsiDocumentManager.getInstance(myProject).getPsiFile(editor.getDocument());
          if (file1 != null) {
            ShowParameterInfoHandler.invoke(myProject, editor, file1, lbraceOffset, highlightedMethod, false, true, null, e -> {
            });
          }
        }
        catch (IndexNotReadyException ignored) { //anything can happen on alarm
        }
      }
    };

    addRequest(() -> documentManager.performLaterWhenAllCommitted(request), settings.PARAMETER_INFO_DELAY);
  }
}
 
Example 10
Source File: ImageOrColorPreviewManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static Collection<PsiElement> getPsiElementsAt(Point point, Editor editor) {
  if (editor.isDisposed()) {
    return Collections.emptySet();
  }

  Project project = editor.getProject();
  if (project == null || project.isDisposed()) {
    return Collections.emptySet();
  }

  final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  final Document document = editor.getDocument();
  PsiFile psiFile = documentManager.getPsiFile(document);
  if (psiFile == null || psiFile instanceof PsiCompiledElement || !psiFile.isValid()) {
    return Collections.emptySet();
  }

  final Set<PsiElement> elements = Collections.newSetFromMap(ContainerUtil.createWeakMap());
  final int offset = editor.logicalPositionToOffset(editor.xyToLogicalPosition(point));
  if (documentManager.isCommitted(document)) {
    ContainerUtil.addIfNotNull(elements, InjectedLanguageUtil.findElementAtNoCommit(psiFile, offset));
  }
  for (PsiFile file : psiFile.getViewProvider().getAllFiles()) {
    ContainerUtil.addIfNotNull(elements, file.findElementAt(offset));
  }

  return elements;
}
 
Example 11
Source File: CodeFoldingManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public CodeFoldingState buildInitialFoldings(@Nonnull final Document document) {
  if (myProject.isDisposed()) {
    return null;
  }
  ApplicationManager.getApplication().assertReadAccessAllowed();
  PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(myProject);
  if (psiDocumentManager.isUncommited(document)) {
    // skip building foldings for uncommitted document, CodeFoldingPass invoked by daemon will do it later
    return null;
  }
  //Do not save/restore folding for code fragments
  final PsiFile file = psiDocumentManager.getPsiFile(document);
  if (file == null || !file.isValid() || !file.getViewProvider().isPhysical() && !ApplicationManager.getApplication().isUnitTestMode()) {
    return null;
  }


  final List<FoldingUpdate.RegionInfo> regionInfos = FoldingUpdate.getFoldingsFor(file, document, true);

  return editor -> {
    ApplicationManager.getApplication().assertIsDispatchThread();
    if (myProject.isDisposed() || editor.isDisposed()) return;
    final FoldingModelEx foldingModel = (FoldingModelEx)editor.getFoldingModel();
    if (!foldingModel.isFoldingEnabled()) return;
    if (isFoldingsInitializedInEditor(editor)) return;
    if (DumbService.isDumb(myProject) && !FoldingUpdate.supportsDumbModeFolding(editor)) return;

    foldingModel.runBatchFoldingOperationDoNotCollapseCaret(new UpdateFoldRegionsOperation(myProject, editor, file, regionInfos, UpdateFoldRegionsOperation.ApplyDefaultStateMode.YES, false, false));
    initFolding(editor);
  };
}
 
Example 12
Source File: MoveElementLeftRightActionHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@RequiredUIAccess
protected boolean isEnabledForCaret(@Nonnull Editor editor, @Nonnull Caret caret, DataContext dataContext) {
  Project project = editor.getProject();
  if (project == null) return false;
  Document document = editor.getDocument();
  if (!(document instanceof DocumentEx)) return false;
  PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(project);
  psiDocumentManager.commitDocument(document);
  PsiFile file = psiDocumentManager.getPsiFile(document);
  if (file == null || !file.isValid()) return false;
  PsiElement[] elementList = getElementList(file, caret.getSelectionStart(), caret.getSelectionEnd());
  return elementList != null;
}
 
Example 13
Source File: CodeStyleSettingsManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Updates document's indent options from indent options providers.
 * <p><b>Note:</b> Calling this method directly when there is an editor associated with the document may cause the editor work
 * incorrectly. To keep consistency with the editor call <code>EditorEx.reinitSettings()</code> instead.
 *
 * @param project  The project of the document.
 * @param document The document to update indent options for.
 */
public static void updateDocumentIndentOptions(@Nonnull Project project, @Nonnull Document document) {
  if (!project.isDisposed()) {
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    if (documentManager != null) {
      PsiFile file = documentManager.getPsiFile(document);
      if (file != null) {
        CommonCodeStyleSettings.IndentOptions indentOptions = getSettings(project).getIndentOptionsByFile(file, null, true, null);
        indentOptions.associateWithDocument(document);
      }
    }
  }
}
 
Example 14
Source File: CodeStyle.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Updates document's indent options from indent options providers.
 * <p><b>Note:</b> Calling this method directly when there is an editor associated with the document may cause the editor work
 * incorrectly. To keep consistency with the editor call {@code EditorEx.reinitSettings()} instead.
 *
 * @param project  The project of the document.
 * @param document The document to update indent options for.
 */
public static void updateDocumentIndentOptions(@Nonnull Project project, @Nonnull Document document) {
  if (!project.isDisposed()) {
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    if (documentManager != null) {
      PsiFile file = documentManager.getPsiFile(document);
      if (file != null) {
        CommonCodeStyleSettings.IndentOptions indentOptions = getSettings(file).getIndentOptionsByFile(file, null, true, null);
        indentOptions.associateWithDocument(document);
      }
    }
  }
}
 
Example 15
Source File: SettingsImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void reinitDocumentIndentOptions() {
  if (myEditor == null || myEditor.isViewer()) return;
  final Project project = myEditor.getProject();
  final DocumentEx document = myEditor.getDocument();

  if (project == null || project.isDisposed()) return;

  final PsiDocumentManager psiManager = PsiDocumentManager.getInstance(project);
  final PsiFile file = psiManager.getPsiFile(document);
  if (file == null) return;

  CodeStyleSettingsManager.updateDocumentIndentOptions(project, document);
}
 
Example 16
Source File: SettingsImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Language getDocumentLanguage(@Nullable Project project, @Nonnull Document document) {
  if (project != null) {
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    PsiFile file = documentManager.getPsiFile(document);
    if (file != null) return file.getLanguage();
  }
  return null;
}
 
Example 17
Source File: CsvTableEditor.java    From intellij-csv-validator with Apache License 2.0 5 votes vote down vote up
@Nullable
public final CsvFile getCsvFile() {
    if (project == null || project.isDisposed()) {
        return null;
    }
    if (this.psiFile == null || !this.psiFile.isValid()) {
        this.document = FileDocumentManager.getInstance().getDocument(this.file);
        PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
        this.psiFile = documentManager.getPsiFile(this.document);
        this.currentSeparator = CsvHelper.getValueSeparator(this.psiFile);
        this.currentEscapeCharacter = CsvHelper.getEscapeCharacter(this.psiFile);
    }
    return this.psiFile instanceof CsvFile ? (CsvFile) psiFile : null;
}
 
Example 18
Source File: TypedHandler.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static void indentBrace(@Nonnull final Project project, @Nonnull final Editor editor, final char braceChar) {
  final int offset = editor.getCaretModel().getOffset() - 1;
  final Document document = editor.getDocument();
  CharSequence chars = document.getCharsSequence();
  if (offset < 0 || chars.charAt(offset) != braceChar) return;

  int spaceStart = CharArrayUtil.shiftBackward(chars, offset - 1, " \t");
  if (spaceStart < 0 || chars.charAt(spaceStart) == '\n' || chars.charAt(spaceStart) == '\r') {
    PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
    documentManager.commitDocument(document);

    final PsiFile file = documentManager.getPsiFile(document);
    if (file == null || !file.isWritable()) return;
    PsiElement element = file.findElementAt(offset);
    if (element == null) return;

    EditorHighlighter highlighter = ((EditorEx)editor).getHighlighter();
    HighlighterIterator iterator = highlighter.createIterator(offset);

    final FileType fileType = file.getFileType();
    BraceMatcher braceMatcher = BraceMatchingUtil.getBraceMatcher(fileType, iterator);
    boolean rBraceToken = braceMatcher.isRBraceToken(iterator, chars, fileType);
    final boolean isBrace = braceMatcher.isLBraceToken(iterator, chars, fileType) || rBraceToken;
    int lBraceOffset = -1;

    if (CodeInsightSettings.getInstance().REFORMAT_BLOCK_ON_RBRACE && rBraceToken && braceMatcher.isStructuralBrace(iterator, chars, fileType) && offset > 0) {
      lBraceOffset = BraceMatchingUtil
              .findLeftLParen(highlighter.createIterator(offset - 1), braceMatcher.getOppositeBraceTokenType(iterator.getTokenType()), editor.getDocument().getCharsSequence(), fileType);
    }
    if (element.getNode() != null && isBrace) {
      DefaultRawTypedHandler handler = ((TypedActionImpl)TypedAction.getInstance()).getDefaultRawTypedHandler();
      handler.beginUndoablePostProcessing();

      final int finalLBraceOffset = lBraceOffset;
      ApplicationManager.getApplication().runWriteAction(() -> {
        try {
          int newOffset;
          if (finalLBraceOffset != -1) {
            RangeMarker marker = document.createRangeMarker(offset, offset + 1);
            CodeStyleManager.getInstance(project).reformatRange(file, finalLBraceOffset, offset, true);
            newOffset = marker.getStartOffset();
            marker.dispose();
          }
          else {
            newOffset = CodeStyleManager.getInstance(project).adjustLineIndent(file, offset);
          }

          editor.getCaretModel().moveToOffset(newOffset + 1);
          editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
          editor.getSelectionModel().removeSelection();
        }
        catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      });
    }
  }
}
 
Example 19
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 20
Source File: PsiAwareLineWrapPositionStrategy.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public int calculateWrapPosition(@Nonnull Document document,
                                 @javax.annotation.Nullable Project project,
                                 int startOffset,
                                 int endOffset,
                                 int maxPreferredOffset,
                                 boolean allowToBeyondMaxPreferredOffset,
                                 boolean virtual) {
  if (virtual && myNonVirtualOnly) {
    LineWrapPositionStrategy implementation = LanguageLineWrapPositionStrategy.INSTANCE.getDefaultImplementation();
    return implementation.calculateWrapPosition(
      document, project, startOffset, endOffset, maxPreferredOffset, allowToBeyondMaxPreferredOffset, virtual
    );
  }

  if (project == null) {
    return -1;
  }

  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  if (documentManager == null) {
    return -1;
  }

  PsiFile psiFile = documentManager.getPsiFile(document);
  if (psiFile == null) {
    return -1;
  }

  PsiElement element = psiFile.findElementAt(maxPreferredOffset);
  if (element == null) {
    return -1;
  }

  for (; element != null && element.getTextRange().getEndOffset() > startOffset; element = getPrevious(element)) {
    if (allowToWrapInside(element)) {
      TextRange textRange = element.getTextRange();
      int start = Math.max(textRange.getStartOffset(), startOffset);
      int end = Math.min(textRange.getEndOffset(), endOffset);
      int result = doCalculateWrapPosition(document, project, start, end, end, false, virtual);
      if (result >= 0) {
        return result;
      }

      // Assume that it's possible to wrap on token boundary (makes sense at least for the tokens that occupy one symbol only).
      if (end <= maxPreferredOffset) {
        return end;
      }

      if (start > startOffset) {
        return start;
      }
    }
  }
  return -1;
}