Promise<TreePath> (Object element) { int editorOffset; if (myFileEditor instanceof TextEditor textEditor) { editorOffset = textEditor.getEditor().getCaretModel().getOffset(); } else { editorOffset = -1; } var state = new StructureViewSelectVisitorState(); TreeVisitor visitor = path -> StructureViewComponent.visitPathForElementSelection(path, element, editorOffset, state); Function<TreePath, Promise<TreePath>> action = path -> { myTree.expandPath(path); TreeUtil.selectPath(myTree, path); TreeUtil.ensureSelection(myTree); return Promises.resolvedPromise(path); }; Function<TreePath, Promise<TreePath>> fallback = new Function<>() { @Override public Promise<TreePath> fun(TreePath path) { if (path == null && state.isOptimizationUsed()) { // Some structure views merge unrelated psi elements into a structure node (MarkdownStructureViewModel). // So turn off the isAncestor() optimization and retry once. state.disableOptimization(); return myAsyncTreeModel.accept(visitor).thenAsync(this); } else { TreePath adjusted = path == null ? state.getBestMatch() : path; if (path == null && adjusted != null && !state.isExactMatch() && element instanceof PsiElement) { Object minChild = findClosestPsiElement((PsiElement)element, adjusted, myAsyncTreeModel); if (minChild != null) adjusted = adjusted.pathByAddingChild(minChild); } return adjusted == null ? Promises.rejectedPromise() : action.fun(adjusted); } } }; return myAsyncTreeModel .accept(visitor) .thenAsync(fallback); }