com.intellij.codeInsight.folding.CodeFoldingManager Java Examples

The following examples show how to use com.intellij.codeInsight.folding.CodeFoldingManager. 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: DesktopPsiAwareTextEditorProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public TextEditorState getStateImpl(final Project project, @Nonnull final Editor editor, @Nonnull final FileEditorStateLevel level) {
  final TextEditorState state = super.getStateImpl(project, editor, level);
  // Save folding only on FULL level. It's very expensive to commit document on every
  // type (caused by undo).
  if (FileEditorStateLevel.FULL == level) {
    // Folding
    if (project != null && !project.isDisposed() && !editor.isDisposed() && project.isInitialized()) {
      state.setFoldingState(CodeFoldingManager.getInstance(project).saveFoldingState(editor));
    }
    else {
      state.setFoldingState(null);
    }
  }

  return state;
}
 
Example #2
Source File: DesktopPsiAwareTextEditorProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void writeState(@Nonnull final FileEditorState _state, @Nonnull final Project project, @Nonnull final Element element) {
  super.writeState(_state, project, element);

  TextEditorState state = (TextEditorState)_state;

  // Foldings
  CodeFoldingState foldingState = state.getFoldingState();
  if (foldingState != null) {
    Element e = new Element(FOLDING_ELEMENT);
    try {
      CodeFoldingManager.getInstance(project).writeFoldingState(foldingState, e);
    }
    catch (WriteExternalException e1) {
      //ignore
    }
    element.addContent(e);
  }
}
 
Example #3
Source File: DesktopPsiAwareTextEditorProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public FileEditorState readState(@Nonnull final Element element, @Nonnull final Project project, @Nonnull final VirtualFile file) {
  final TextEditorState state = (TextEditorState)super.readState(element, project, file);

  // Foldings
  Element child = element.getChild(FOLDING_ELEMENT);
  Document document = FileDocumentManager.getInstance().getCachedDocument(file);
  if (child != null) {
    if (document == null) {
      final Element detachedStateCopy = child.clone();
      state.setDelayedFoldState(() -> {
        Document document1 = FileDocumentManager.getInstance().getCachedDocument(file);
        return document1 == null ? null : CodeFoldingManager.getInstance(project).readFoldingState(detachedStateCopy, document1);
      });
    }
    else {
      //PsiDocumentManager.getInstance(project).commitDocument(document);
      state.setFoldingState(CodeFoldingManager.getInstance(project).readFoldingState(child, document));
    }
  }
  return state;
}
 
Example #4
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 #5
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 #6
Source File: DesktopPsiAwareTextEditorImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
protected Runnable loadEditorInBackground() {
  Runnable baseAction = super.loadEditorInBackground();
  PsiFile psiFile = PsiManager.getInstance(myProject).findFile(myFile);
  Document document = FileDocumentManager.getInstance().getDocument(myFile);
  CodeFoldingState foldingState = document != null && !myProject.isDefault()
                                  ? CodeFoldingManager.getInstance(myProject).buildInitialFoldings(document)
                                  : null;
  return () -> {
    baseAction.run();
    if (foldingState != null) {
      foldingState.setToEditor(getEditor());
    }
    if (psiFile != null && psiFile.isValid()) {
      DaemonCodeAnalyzer.getInstance(myProject).restart(psiFile);
    }
    EditorNotifications.getInstance(myProject).updateNotifications(myFile);
  };
}
 
Example #7
Source File: CodeFoldingConfigurable.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void afterApply() {
  super.afterApply();

  final List<Pair<Editor, Project>> toUpdate = new ArrayList<Pair<Editor, Project>>();
  for (final Editor editor : EditorFactory.getInstance().getAllEditors()) {
    final Project project = editor.getProject();
    if (project != null && !project.isDefault()) {
      toUpdate.add(Pair.create(editor, project));
    }
  }

  ApplicationManager.getApplication().invokeLater(() -> {
    for (Pair<Editor, Project> each : toUpdate) {
      if (each.second == null || each.second.isDisposed()) {
        continue;
      }
      final CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(each.second);
      if (foldingManager != null) {
        foldingManager.buildInitialFoldings(each.first);
      }
    }
    EditorGeneralConfigurable.reinitAllEditors();
  }, ModalityState.NON_MODAL);
}
 
Example #8
Source File: DesktopPsiAwareTextEditorProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void setStateImpl(final Project project, final Editor editor, final TextEditorState state) {
  super.setStateImpl(project, editor, state);
  // Folding
  final CodeFoldingState foldState = state.getFoldingState();
  if (project != null && foldState != null && DesktopAsyncEditorLoader.isEditorLoaded(editor)) {
    if (!PsiDocumentManager.getInstance(project).isCommitted(editor.getDocument())) {
      PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
      LOG.error("File should be parsed when changing editor state, otherwise UI might be frozen for a considerable time");
    }
    editor.getFoldingModel().runBatchFoldingOperation(() -> CodeFoldingManager.getInstance(project).restoreFoldingState(editor, foldState));
  }
}
 
Example #9
Source File: BashFoldingBuilderPerformanceTest.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
public void testFolding() {
    myFixture.configureByFile("functions_issue96.bash");
    myFixture.getEditor().getCaretModel().moveToOffset(myFixture.getEditor().getDocument().getTextLength());

    PlatformTestUtil.startPerformanceTest(getTestName(true), 10 * 250, () -> {
        for (int i = 0; i < 10; i++) {
            long start = System.currentTimeMillis();
            CodeFoldingManager.getInstance(getProject()).buildInitialFoldings(myFixture.getEditor());

            myFixture.type("echo hello world\n");

            System.out.printf("Cycle duration: %d\n", System.currentTimeMillis() - start);
        }
    }).usesAllCPUCores().assertTiming();
}
 
Example #10
Source File: DesktopPsiAwareTextEditorImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void dispose() {
  CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(myProject);
  if (foldingManager != null) {
    foldingManager.releaseFoldings(getEditor());
  }
  super.dispose();
}
 
Example #11
Source File: RestoreFoldArrangementCallback.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void afterArrangement(@Nonnull final List<ArrangementMoveInfo> moveInfos) {
  // Restore state for the PSI elements not affected by arrangement.
  Project project = myEditor.getProject();
  if (myCodeFoldingState != null && project != null) {
    final CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(project);
    foldingManager.updateFoldRegions(myEditor);
    myEditor.getFoldingModel().runBatchFoldingOperation(new Runnable() {
      @Override
      public void run() {
        foldingManager.restoreFoldingState(myEditor, myCodeFoldingState);
      }
    });
  }
}
 
Example #12
Source File: RestoreFoldArrangementCallback.java    From consulo with Apache License 2.0 5 votes vote down vote up
public RestoreFoldArrangementCallback(@Nonnull Editor editor) {
  myEditor = editor;

  Project project = editor.getProject();
  if (project == null) {
    myCodeFoldingState = null;
  }
  else {
    final CodeFoldingManager foldingManager = CodeFoldingManager.getInstance(editor.getProject());
    myCodeFoldingState = foldingManager.saveFoldingState(editor);
  }
}
 
Example #13
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 #14
Source File: SoftWrapApplianceOnDocumentModificationTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testFoldRegionsUpdate() throws IOException {
  String text =
          "import java.util.List;\n" +
          "import java.util.ArrayList;\n" +
          "\n" +
          "class Test {\n" +
          "}";
  init(40, text);

  final int foldStartOffset = "import".length() + 1;
  int foldEndOffset = text.indexOf("class") - 2;
  addCollapsedFoldRegion(foldStartOffset, foldEndOffset, "...");

  // Simulate addition of the new import that modifies existing fold region.
  WriteCommandAction.runWriteCommandAction(getProject(), () -> myEditor.getDocument().insertString(foldEndOffset, "\nimport java.util.Date;\n"));

  final FoldingModel foldingModel = myEditor.getFoldingModel();
  foldingModel.runBatchFoldingOperation(() -> {
    FoldRegion oldFoldRegion = getFoldRegion(foldStartOffset);
    assertNotNull(oldFoldRegion);
    foldingModel.removeFoldRegion(oldFoldRegion);

    int newFoldEndOffset = myEditor.getDocument().getText().indexOf("class") - 2;
    FoldRegion newFoldRegion = foldingModel.addFoldRegion(foldStartOffset, newFoldEndOffset, "...");
    assertNotNull(newFoldRegion);
    newFoldRegion.setExpanded(false);
  });
  CodeFoldingManager.getInstance(getProject()).updateFoldRegions(myEditor);
  assertEquals(new VisualPosition(2, 0), myEditor.logicalToVisualPosition(new LogicalPosition(5, 0)));
}
 
Example #15
Source File: FoldingTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private String getFoldingDescription(@Nonnull String content, @Nonnull String fileName, boolean doCheckCollapseStatus) {
  FileType fileTypeByFileName = FileTypeManager.getInstance().getFileTypeByFileName(fileName);

  PsiFile file = createFile(fileName, fileTypeByFileName, content);

  final FileEditorManager fileEditorManager = FileEditorManager.getInstance(myProject);

  Editor editor = fileEditorManager.openTextEditor(new OpenFileDescriptor(myProject, file.getVirtualFile()), false);

  CodeFoldingManager.getInstance(myProject).buildInitialFoldings(editor);

  final FoldingModel model = editor.getFoldingModel();
  final FoldRegion[] foldingRegions = model.getAllFoldRegions();
  final List<Border> borders = new LinkedList<Border>();

  for (FoldRegion region : foldingRegions) {
    borders.add(new Border(Border.LEFT, region.getStartOffset(), region.getPlaceholderText(), region.isExpanded()));
    borders.add(new Border(Border.RIGHT, region.getEndOffset(), "", region.isExpanded()));
  }
  Collections.sort(borders);

  StringBuilder result = new StringBuilder(editor.getDocument().getText());
  for (Border border : borders) {
    result.insert(border.getOffset(), border.isSide() == Border.LEFT ? "<fold text=\'" + border.getText() + "\'" +
                                                                       (doCheckCollapseStatus ? " expand=\'" +
                                                                                                border.isExpanded() +
                                                                                                "\'" : "") +
                                                                       ">" : END_FOLD);
  }

  return result.toString();
}
 
Example #16
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_should_not_fold_single_line() {
	// Given
	myFixture.configureByText("foo.g4", "grammar foo;\n @members { int i; }\n");

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

	// Then
	FoldRegion[] allFoldRegions = myFixture.getEditor().getFoldingModel().getAllFoldRegions();
	assertEquals(0, allFoldRegions.length);
}
 
Example #17
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 #18
Source File: CodeFoldingPass.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
@Override
public void doCollectInformation(@Nonnull ProgressIndicator progress) {
  final boolean firstTime = isFirstTime(myFile, myEditor, THE_FIRST_TIME);
  myRunnable = CodeFoldingManager.getInstance(myProject).updateFoldRegionsAsync(myEditor, firstTime);
}