eclipseeclipse-plugin

User-defined code folding regions in Eclipse


Is there any built-in functionality or plugin that would allow me to define my own custom regions for code folding? I am using version 4.8.0 (Photon release)

In particular, I am interested in folding certain parts of .java files where I am needing to declare a lot of variables.


Solution

  • To add folding regions to Java sources, you can implement the extension "org.eclipse.jdt.ui.foldingStructureProvider". To do this, you create an eclipse plug-in project (requires Eclipse PDE) and add an extension point to your plugin.xml. Then you create a class that implements IJavaFoldingStructureProvider and possibly IJavaFoldingStructureProviderExtension.

    Folding regions are added like this:

    FoldingStructureComputationContext context
    
    IRegion normalized = alignRegion(new Region(offset, length), context);
    if (normalized != null) {
        Position position = createMemberPosition(normalized, (IMember) element);
        if (position != null) {
            boolean isCollapsed = false, isComment = false;
            context.addProjectionRange(new JavaProjectionAnnotation(isCollapsed, element, isComment), position);
        }
    }
    

    See DefaultJavaFoldingStructureProvider for alignRegion, createMemberPosition, etc. offset and length are determined by your code.