com.intellij.openapi.editor.FoldRegion Java Examples

The following examples show how to use com.intellij.openapi.editor.FoldRegion. 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: UpdateFoldRegionsOperation.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  EditorFoldingInfo info = EditorFoldingInfo.get(myEditor);
  FoldingModelEx foldingModel = (FoldingModelEx)myEditor.getFoldingModel();
  Map<TextRange, Boolean> rangeToExpandStatusMap = new THashMap<>();

  removeInvalidRegions(info, foldingModel, rangeToExpandStatusMap);

  Map<FoldRegion, Boolean> shouldExpand = new THashMap<>();
  Map<FoldingGroup, Boolean> groupExpand = new THashMap<>();
  List<FoldRegion> newRegions = addNewRegions(info, foldingModel, rangeToExpandStatusMap, shouldExpand, groupExpand);

  applyExpandStatus(newRegions, shouldExpand, groupExpand);

  foldingModel.clearDocumentRangesModificationStatus();
}
 
Example #2
Source File: CollapseExpandDocCommentsHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void invokeInWriteAction(@Nonnull Project project, @Nonnull final Editor editor, @Nonnull PsiFile file){
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(project);
  foldingManager.updateFoldRegions(editor);
  final FoldRegion[] allFoldRegions = editor.getFoldingModel().getAllFoldRegions();
  Runnable processor = new Runnable() {
    @Override
    public void run() {
      for (FoldRegion region : allFoldRegions) {
        PsiElement element = EditorFoldingInfo.get(editor).getPsiElement(region);
        if (element instanceof PsiDocCommentBase) {
          region.setExpanded(myExpand);
        }
      }
    }
  };
  editor.getFoldingModel().runBatchFoldingOperation(processor);
}
 
Example #3
Source File: DocumentFoldingInfo.java    From consulo with Apache License 2.0 6 votes vote down vote up
void loadFromEditor(@Nonnull Editor editor) {
  ApplicationManager.getApplication().assertIsDispatchThread();
  LOG.assertTrue(!editor.isDisposed());
  clear();

  FoldRegion[] foldRegions = editor.getFoldingModel().getAllFoldRegions();
  for (FoldRegion region : foldRegions) {
    if (!region.isValid()) continue;
    boolean expanded = region.isExpanded();
    String signature = region.getUserData(UpdateFoldRegionsOperation.SIGNATURE);
    if (signature == UpdateFoldRegionsOperation.NO_SIGNATURE) continue;
    Boolean storedCollapseByDefault = region.getUserData(UpdateFoldRegionsOperation.COLLAPSED_BY_DEFAULT);
    boolean collapseByDefault = storedCollapseByDefault != null && storedCollapseByDefault && !FoldingUtil.caretInsideRange(editor, TextRange.create(region));
    if (collapseByDefault == expanded || signature == null) {
      if (signature != null) {
        myInfos.add(new Info(signature, expanded));
      }
      else {
        RangeMarker marker = editor.getDocument().createRangeMarker(region.getStartOffset(), region.getEndOffset());
        myRangeMarkers.add(marker);
        marker.putUserData(FOLDING_INFO_KEY, new FoldingInfo(region.getPlaceholderText(), expanded));
      }
    }
  }
}
 
Example #4
Source File: CopyPasteFoldingProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public List<FoldingTransferableData> collectTransferableData(final PsiFile file, final Editor editor, final int[] startOffsets, final int[] endOffsets) {
  // might be slow
  //CodeFoldingManager.getInstance(file.getManager().getProject()).updateFoldRegions(editor);

  final ArrayList<FoldingData> list = new ArrayList<FoldingData>();
  final FoldRegion[] regions = editor.getFoldingModel().getAllFoldRegions();
  for (final FoldRegion region : regions) {
    if (!region.isValid()) continue;
    for (int j = 0; j < startOffsets.length; j++) {
      if (startOffsets[j] <= region.getStartOffset() && region.getEndOffset() <= endOffsets[j]) {
        list.add(
                new FoldingData(
                        region.getStartOffset() - startOffsets[j],
                        region.getEndOffset() - startOffsets[j],
                        region.isExpanded()
                )
        );
      }
    }
  }

  return Collections.singletonList(new FoldingTransferableData(list.toArray(new FoldingData[list.size()])));
}
 
Example #5
Source File: FoldingModelSupport.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
protected TIntFunction getLineConvertor(final int index) {
  return new TIntFunction() {
    @Override
    public int execute(int value) {
      updateLineNumbers(false);
      for (FoldedBlock folding : getFoldedBlocks()) { // TODO: avoid full scan - it could slowdown painting
        int line = folding.getLine(index);
        if (line == -1) continue;
        if (line > value) break;
        FoldRegion region = folding.getRegion(index);
        if (line == value && region != null && !region.isExpanded()) return -1;
      }
      return value;
    }
  };
}
 
Example #6
Source File: EditorView.java    From consulo with Apache License 2.0 6 votes vote down vote up
public int offsetToVisualColumnInFoldRegion(@Nonnull FoldRegion region, int offset, boolean leanTowardsLargerOffsets) {
  if (offset < 0 || offset == 0 && !leanTowardsLargerOffsets) return 0;
  String text = region.getPlaceholderText();
  if (offset > text.length()) {
    offset = text.length();
    leanTowardsLargerOffsets = true;
  }
  int logicalColumn = LogicalPositionCache.calcColumn(text, 0, 0, offset, getTabSize());
  int maxColumn = 0;
  for (LineLayout.VisualFragment fragment : getFoldRegionLayout(region).getFragmentsInVisualOrder(0)) {
    int startLC = fragment.getStartLogicalColumn();
    int endLC = fragment.getEndLogicalColumn();
    if (logicalColumn > startLC && logicalColumn < endLC || logicalColumn == startLC && leanTowardsLargerOffsets || logicalColumn == endLC && !leanTowardsLargerOffsets) {
      return fragment.logicalToVisualColumn(logicalColumn);
    }
    maxColumn = fragment.getEndVisualColumn();
  }
  return maxColumn;
}
 
Example #7
Source File: ExpandRegionAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void expandRegionAtOffset(@Nonnull Project project, @Nonnull final Editor editor, final int offset) {
  CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(project);
  foldingManager.updateFoldRegions(editor);

  final int line = editor.getDocument().getLineNumber(offset);
  Runnable processor = () -> {
    FoldRegion region = FoldingUtil.findFoldRegionStartingAtLine(editor, line);
    if (region != null && !region.isExpanded()) {
      region.setExpanded(true);
    }
    else {
      FoldRegion[] regions = FoldingUtil.getFoldRegionsAtOffset(editor, offset);
      for (int i = regions.length - 1; i >= 0; i--) {
        region = regions[i];
        if (!region.isExpanded()) {
          region.setExpanded(true);
          break;
        }
      }
    }
  };
  editor.getFoldingModel().runBatchFoldingOperation(processor);
}
 
Example #8
Source File: FoldingUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static FoldRegion findFoldRegionStartingAtLine(@Nonnull Editor editor, int line) {
  if (line < 0 || line >= editor.getDocument().getLineCount()) {
    return null;
  }
  FoldRegion result = null;
  FoldRegion[] regions = editor.getFoldingModel().getAllFoldRegions();
  for (FoldRegion region : regions) {
    if (!region.isValid()) {
      continue;
    }
    if (region.getDocument().getLineNumber(region.getStartOffset()) == line) {
      if (result != null) return null;
      result = region;
    }
  }
  return result;
}
 
Example #9
Source File: BaseFoldingHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Returns fold regions inside selection, or all regions in editor, if selection doesn't exist or doesn't contain fold regions.
 */
protected List<FoldRegion> getFoldRegionsForSelection(@Nonnull Editor editor, @Nullable Caret caret) {
  FoldRegion[] allRegions = editor.getFoldingModel().getAllFoldRegions();
  if (caret == null) {
    caret = editor.getCaretModel().getPrimaryCaret();
  }
  if (caret.hasSelection()) {
    List<FoldRegion> result = new ArrayList<>();
    for (FoldRegion region : allRegions) {
      if (region.getStartOffset() >= caret.getSelectionStart() && region.getEndOffset() <= caret.getSelectionEnd()) {
        result.add(region);
      }
    }
    if (!result.isEmpty()) {
      return result;
    }
  }
  return Arrays.asList(allRegions);
}
 
Example #10
Source File: FoldingModelSupport.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private BooleanGetter getHighlighterCondition(@Nonnull final FoldedBlock[] block, final int index) {
  return new BooleanGetter() {
    @Override
    public boolean get() {
      if (!myEditors[index].getFoldingModel().isFoldingEnabled()) return false;

      for (FoldedBlock folding : block) {
        FoldRegion region = folding.getRegion(index);
        boolean visible = region != null && region.isValid() && !region.isExpanded();
        if (folding == FoldedBlock.this) return visible;
        if (visible) return false; // do not paint separator, if 'parent' folding is collapsed
      }
      return false;
    }
  };
}
 
Example #11
Source File: VisualLinesIterator.java    From consulo with Apache License 2.0 5 votes vote down vote up
private boolean isCollapsed(int offset) {
  while (foldRegion < myFoldRegions.length) {
    FoldRegion region = myFoldRegions[foldRegion];
    if (offset <= region.getStartOffset()) return false;
    if (offset <= region.getEndOffset()) return true;
    foldRegion++;
  }
  return false;
}
 
Example #12
Source File: VisualLineFragmentsIterator.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void init(EditorView view, int visualLine, int startOffset, int startLogicalLine, int currentOrPrevWrapIndex, int nextFoldingIndex,
                  @Nullable Runnable quickEvaluationListener, boolean align) {
  myQuickEvaluationListener = quickEvaluationListener;
  myView = view;
  DesktopEditorImpl editor = view.getEditor();
  myScaleContext = JBUI.ScaleContext.create(editor.getContentComponent());
  if (align && visualLine != -1 && editor.isRightAligned()) {
    myFragment = new RightAlignedFragment(view.getRightAlignmentLineStartX(visualLine) - myView.getInsets().left);
  }
  myDocument = editor.getDocument();
  FoldingModelEx foldingModel = editor.getFoldingModel();
  FoldRegion[] regions = foldingModel.fetchTopLevel();
  myRegions = regions == null ? FoldRegion.EMPTY_ARRAY : regions;
  SoftWrapModelImpl softWrapModel = editor.getSoftWrapModel();
  List<? extends SoftWrap> softWraps = softWrapModel.getRegisteredSoftWraps();
  SoftWrap currentOrPrevWrap = currentOrPrevWrapIndex < 0 || currentOrPrevWrapIndex >= softWraps.size() ? null : softWraps.get(currentOrPrevWrapIndex);
  SoftWrap followingWrap = currentOrPrevWrapIndex + 1 < 0 || currentOrPrevWrapIndex + 1 >= softWraps.size() ? null : softWraps.get(currentOrPrevWrapIndex + 1);

  myVisualLineStartOffset = mySegmentStartOffset = startOffset;

  myCurrentFoldRegionIndex = nextFoldingIndex;
  myCurrentEndLogicalLine = startLogicalLine;
  myCurrentX = myView.getInsets().left;
  if (mySegmentStartOffset == 0) {
    myCurrentX += myView.getPrefixTextWidthInPixels();
  }
  else if (currentOrPrevWrap != null && mySegmentStartOffset == currentOrPrevWrap.getStart()) {
    myCurrentX += currentOrPrevWrap.getIndentInPixels();
    myCurrentVisualColumn = currentOrPrevWrap.getIndentInColumns();
  }
  myNextWrapOffset = followingWrap == null ? Integer.MAX_VALUE : followingWrap.getStart();
  setInlaysAndFragmentIterator();
}
 
Example #13
Source File: FoldingTransformation.java    From consulo with Apache License 2.0 5 votes vote down vote up
private FoldRegion findFoldRegion(int line) {
  int index = Arrays.binarySearch(myFoldBeginings, line);
  FoldRegion region;
  if (index >= 0) region = myCollapsed.get(index);
  else {
    index = -index - 1;
    if (index == 0) return null;
    region = myCollapsed.get(index - 1);
  }
  if (getEndLine(region) < line) return null;
  return region;
}
 
Example #14
Source File: FoldingModelWindow.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<FoldRegion> getGroupedRegions(FoldingGroup group) {
  List<FoldRegion> hostRegions = myDelegate.getGroupedRegions(group);
  List<FoldRegion> result = new ArrayList<>();
  for (FoldRegion hostRegion : hostRegions) {
    FoldingRegionWindow window = getWindowRegion(hostRegion);
    if (window != null) result.add(window);
  }
  return result;
}
 
Example #15
Source File: FoldingModelSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void onFoldProcessingEnd() {
  if (myModifiedRegions.isEmpty()) return;
  myDuringSynchronize = true;
  try {
    for (int i = 0; i < myCount; i++) {
      if (i == myIndex) continue;
      final int pairedIndex = i;
      myEditors[pairedIndex].getFoldingModel().runBatchFoldingOperation(new Runnable() {
        @Override
        public void run() {
          for (FoldedBlock folding : getFoldedBlocks()) {
            FoldRegion region = folding.getRegion(myIndex);
            if (region == null || !region.isValid()) continue;
            if (myModifiedRegions.contains(region)) {
              FoldRegion pairedRegion = folding.getRegion(pairedIndex);
              if (pairedRegion == null || !pairedRegion.isValid()) continue;
              pairedRegion.setExpanded(region.isExpanded());
            }
          }
        }
      });
    }

    myModifiedRegions.clear();
  }
  finally {
    myDuringSynchronize = false;
  }
}
 
Example #16
Source File: FoldingModelSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void process(@Nonnull Handler handler) {
  for (FoldedBlock[] block : myFoldings) {
    for (FoldedBlock folding : block) {
      FoldRegion region1 = folding.getRegion(myLeft);
      FoldRegion region2 = folding.getRegion(myRight);
      if (region1 == null || !region1.isValid() || region1.isExpanded()) continue;
      if (region2 == null || !region2.isValid() || region2.isExpanded()) continue;
      int line1 = myEditors[myLeft].getDocument().getLineNumber(region1.getStartOffset());
      int line2 = myEditors[myRight].getDocument().getLineNumber(region2.getStartOffset());
      if (!handler.process(line1, line2)) return;
      break;
    }
  }
}
 
Example #17
Source File: FoldingUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static FoldRegion[] getFoldRegionsAtOffset(Editor editor, int offset) {
  List<FoldRegion> list = new ArrayList<>();
  FoldRegion[] allRegions = editor.getFoldingModel().getAllFoldRegions();
  for (FoldRegion region : allRegions) {
    if (region.getStartOffset() <= offset && offset <= region.getEndOffset()) {
      list.add(region);
    }
  }

  FoldRegion[] regions = list.toArray(FoldRegion.EMPTY_ARRAY);
  Arrays.sort(regions, Collections.reverseOrder(RangeMarker.BY_START_OFFSET));
  return regions;
}
 
Example #18
Source File: FoldingModelSupport.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void destroyFoldings(final int index) {
  final FoldingModelEx model = myEditors[index].getFoldingModel();
  model.runBatchFoldingOperation(new Runnable() {
    @Override
    public void run() {
      for (FoldedBlock folding : getFoldedBlocks()) {
        FoldRegion region = folding.getRegion(index);
        if (region != null) model.removeFoldRegion(region);
      }
    }
  });
}
 
Example #19
Source File: FoldingTransformation.java    From consulo with Apache License 2.0 5 votes vote down vote up
public FoldingTransformation(Editor editor) {
  myEditor = editor;
  FoldRegion[] foldRegions = myEditor.getFoldingModel().getAllFoldRegions();
  Arrays.sort(foldRegions, RangeMarker.BY_START_OFFSET);
  TIntArrayList foldBeginings = new TIntArrayList();
  for (FoldRegion foldRegion : foldRegions) {
    if (!foldRegion.isValid() || foldRegion.isExpanded()) continue;
    foldBeginings.add(getStartLine(foldRegion));
    myCollapsed.add(foldRegion);
  }
  myFoldBeginings = foldBeginings.toNativeArray();
}
 
Example #20
Source File: UpdateFoldRegionsOperation.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void applyExpandStatus(@Nonnull List<? extends FoldRegion> newRegions, @Nonnull Map<FoldRegion, Boolean> shouldExpand, @Nonnull Map<FoldingGroup, Boolean> groupExpand) {
  for (final FoldRegion region : newRegions) {
    final FoldingGroup group = region.getGroup();
    final Boolean expanded = group == null ? shouldExpand.get(region) : groupExpand.get(group);

    if (expanded != null) {
      region.setExpanded(expanded.booleanValue());
    }
  }
}
 
Example #21
Source File: FoldingModelWindow.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public FoldRegion createFoldRegion(int startOffset, int endOffset, @Nonnull String placeholder, FoldingGroup group, boolean neverExpands) {
  TextRange hostRange = myDocumentWindow.injectedToHost(new TextRange(startOffset, endOffset));
  if (hostRange.getLength() < 2) return null;
  FoldRegion hostRegion = myDelegate.createFoldRegion(hostRange.getStartOffset(), hostRange.getEndOffset(), placeholder, group, neverExpands);
  if (hostRegion == null) return null;
  int startShift = Math.max(0, myDocumentWindow.hostToInjected(hostRange.getStartOffset()) - startOffset);
  int endShift = Math.max(0, endOffset - myDocumentWindow.hostToInjected(hostRange.getEndOffset()) - startShift);
  FoldingRegionWindow window = new FoldingRegionWindow(myDocumentWindow, myEditorWindow, hostRegion, startShift, endShift);
  hostRegion.putUserData(FOLD_REGION_WINDOW, window);
  return window;
}
 
Example #22
Source File: EditorView.java    From consulo with Apache License 2.0 5 votes vote down vote up
public int visualColumnToOffsetInFoldRegion(@Nonnull FoldRegion region, int visualColumn, boolean leansRight) {
  if (visualColumn < 0 || visualColumn == 0 && !leansRight) return 0;
  String text = region.getPlaceholderText();
  for (LineLayout.VisualFragment fragment : getFoldRegionLayout(region).getFragmentsInVisualOrder(0)) {
    int startVC = fragment.getStartVisualColumn();
    int endVC = fragment.getEndVisualColumn();
    if (visualColumn > startVC && visualColumn < endVC || visualColumn == startVC && leansRight || visualColumn == endVC && !leansRight) {
      int logicalColumn = fragment.visualToLogicalColumn(visualColumn);
      return LogicalPositionCache.calcOffset(text, logicalColumn, 0, 0, text.length(), getTabSize());
    }
  }
  return text.length();
}
 
Example #23
Source File: ANTLRv4FoldingBuilderTest.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void test_folding_should_not_throw_on_incomplete_prequel() {
	// Given
	myFixture.configureByText("foo.g4", "grammar foo;\n @\n");

	// When
	CodeFoldingManager.getInstance(getProject()).buildInitialFoldings(myFixture.getEditor());

	// Then
	FoldRegion[] allFoldRegions = myFixture.getEditor().getFoldingModel().getAllFoldRegions();
	assertEquals(0, allFoldRegions.length);
}
 
Example #24
Source File: VisualLineFragmentsIterator.java    From consulo with Apache License 2.0 5 votes vote down vote up
private int getFoldRegionWidthInColumns(FoldRegion foldRegion) {
  int maxVisualColumn = 0;
  for (LineLayout.VisualFragment fragment : myView.getFoldRegionLayout(foldRegion).getFragmentsInVisualOrder(0)) {
    maxVisualColumn = fragment.getEndVisualColumn();
  }
  return maxVisualColumn;
}
 
Example #25
Source File: FoldRegionsTree.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
FoldRegion fetchOutermost(int offset) {
  if (!isFoldingEnabled()) return null;
  CachedData cachedData = ensureAvailableData();

  final int[] starts = cachedData.topStartOffsets;
  final int[] ends = cachedData.topEndOffsets;
  if (starts == null || ends == null) {
    return null;
  }

  int i = ObjectUtil.binarySearch(0, ends.length, mid -> ends[mid] < offset ? -1 : starts[mid] > offset ? 1 : 0);
  return i < 0 ? null : cachedData.topLevelRegions[i];
}
 
Example #26
Source File: FoldRegionsTree.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
FoldRegion[] fetchVisible() {
  if (!isFoldingEnabled()) return null;
  CachedData cachedData = ensureAvailableData();

  return cachedData.visibleRegions;
}
 
Example #27
Source File: FoldRegionsTree.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
FoldRegion[] fetchCollapsedAt(int offset) {
  if (!isFoldingEnabled()) return FoldRegion.EMPTY_ARRAY;
  List<FoldRegion> allCollapsed = new ArrayList<>();
  myMarkerTree.processContaining(offset, region -> {
    if (!region.isExpanded() && containsStrict(region, offset)) {
      allCollapsed.add(region);
    }
    return true;
  });
  return toFoldArray(allCollapsed);
}
 
Example #28
Source File: FoldRegionsTree.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
FoldRegion[] fetchAllRegions() {
  if (!isFoldingEnabled()) return FoldRegion.EMPTY_ARRAY;
  List<FoldRegion> regions = new ArrayList<>();
  myMarkerTree.processOverlappingWith(0, Integer.MAX_VALUE, new CommonProcessors.CollectProcessor<>(regions));
  return toFoldArray(regions);
}
 
Example #29
Source File: CollapseRegionAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public CollapseRegionAction() {
  super(new BaseFoldingHandler() {
    @Override
    public void doExecute(@Nonnull final Editor editor, @Nullable Caret caret, DataContext dataContext) {
      CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(editor.getProject());
      foldingManager.updateFoldRegions(editor);

      final int line = editor.getCaretModel().getLogicalPosition().line;

      Runnable processor = () -> {
        FoldRegion region = FoldingUtil.findFoldRegionStartingAtLine(editor, line);
        if (region != null && region.isExpanded()) {
          region.setExpanded(false);
        }
        else {
          int offset = editor.getCaretModel().getOffset();
          FoldRegion[] regions = FoldingUtil.getFoldRegionsAtOffset(editor, offset);
          for (FoldRegion region1 : regions) {
            if (region1.isExpanded()) {
              region1.setExpanded(false);
              break;
            }
          }
        }
      };
      editor.getFoldingModel().runBatchFoldingOperation(processor);
    }
  });
}
 
Example #30
Source File: FoldingModelWindow.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void removeFoldRegion(@Nonnull FoldRegion region) {
  myDelegate.removeFoldRegion(((FoldingRegionWindow)region).getDelegate());
}