void (@NotNull final Editor editor, @Nullable Caret caret, DataContext dataContext) { if (caret == null) { caret = editor.getCaretModel().getPrimaryCaret(); } int offset = caret.getOffset(); FoldRegion rootRegion = null; if (!expandAll) { rootRegion = FoldingUtil.findFoldRegionStartingAtLine(editor, editor.getDocument().getLineNumber(offset)); if (rootRegion == null) { FoldRegion[] regions = FoldingUtil.getFoldRegionsAtOffset(editor, offset); if (regions.length > 0) { rootRegion = regions[0]; } } if (rootRegion == null) { return; } } final FoldRegion root = rootRegion; final int[] rootLevel = new int[] {root == null ? 1 : -1}; editor.getFoldingModel().runBatchFoldingOperation(() -> { Iterator<FoldRegion> regionTreeIterator = FoldingUtil.createFoldTreeIterator(editor); Deque<FoldRegion> currentStack = new LinkedList<>(); while (regionTreeIterator.hasNext()) { FoldRegion region = regionTreeIterator.next(); while (!currentStack.isEmpty() && !isChild(currentStack.peek(), region)) { if (currentStack.remove() == root) { rootLevel[0] = -1; } } currentStack.push(region); int currentLevel = currentStack.size(); if (region == root) { rootLevel[0] = currentLevel; } if (rootLevel[0] >= 0) { int relativeLevel = currentLevel - rootLevel[0]; if (relativeLevel < level) { region.setExpanded(true); } else if (relativeLevel == level) { region.setExpanded(false); } } } }); }