diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/folding/FoldingTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/folding/FoldingTest.java new file mode 100644 index 00000000000..831888349aa --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/folding/FoldingTest.java @@ -0,0 +1,363 @@ +/******************************************************************************* + * Copyright (c) 2025 Vector Informatik GmbH and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Vector Informatik GmbH - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.folding; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.eclipse.jface.text.IRegion; +import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.Region; +import org.eclipse.jface.text.source.Annotation; +import org.eclipse.jface.text.source.projection.ProjectionAnnotation; +import org.eclipse.jface.text.source.projection.ProjectionAnnotationModel; +import org.eclipse.jface.text.source.projection.ProjectionViewer; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jdt.ui.tests.core.rules.ProjectTestSetup; + +import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; +import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; +import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; + +public class FoldingTest { + @Rule + public ProjectTestSetup projectSetup= new ProjectTestSetup(); + + private IJavaProject jProject; + + private IPackageFragmentRoot sourceFolder; + + private IPackageFragment packageFragment; + + @Before + public void setUp() throws CoreException { + jProject= projectSetup.getProject(); + sourceFolder= jProject.findPackageFragmentRoot(jProject.getResource().getFullPath().append("src")); + if (sourceFolder == null) { + sourceFolder= JavaProjectHelper.addSourceContainer(jProject, "src"); + } + packageFragment= sourceFolder.createPackageFragment("org.example.test", false, null); + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setValue(PreferenceConstants.EDITOR_NEW_FOLDING_ENABLED, true); + } + + @After + public void tearDown() throws CoreException { + JavaProjectHelper.delete(jProject); + } + + @Test + public void testMethodDeclarationFoldingWithSameLineStart() throws Exception { + String str= """ + package org.example.test; + public class Q { + void a() { //here should be an annotation + int i = 0; + }void b() { //here should be an annotation + } + } + """; + List regions= getProjectionRangesOfFile(str); + assertCodeHasRegions(str, 2); + regions.sort((r1, r2) -> Integer.compare(r1.getOffset(), r2.getOffset())); + IRegion methodARegion= regions.get(0); + IRegion methodBRegion= regions.get(1); + int methodAEnd= methodARegion.getOffset() + methodARegion.getLength(); + int methodBStart= methodBRegion.getOffset(); + + assertTrue(methodBStart >= methodAEnd); + } + + private List getProjectionRangesOfFile(String str) throws Exception { + ICompilationUnit cu= packageFragment.createCompilationUnit("TestFolding.java", str, true, null); + JavaEditor editor= (JavaEditor) EditorUtility.openInEditor(cu); + ProjectionAnnotationModel model= editor.getAdapter(ProjectionAnnotationModel.class); + List regions= new ArrayList<>(); + Iterator it= model.getAnnotationIterator(); + while (it.hasNext()) { + Annotation a= it.next(); + if (a instanceof ProjectionAnnotation) { + Position p= model.getPosition(a); + regions.add(new Region(p.getOffset(), p.getLength())); + } + } + return regions; + } + + @Test + public void testCompilationUnitFolding() throws Exception { + String str= """ + package org.example.test; + public class A { //here should not be an annotation + } + """; + assertCodeHasRegions(str, 0); + } + + @Test + public void testTypeDeclarationFolding() throws Exception { + String str= """ + package org.example.test; + public class B { + class Inner { //here should be an annotation + } + } + """; + assertCodeHasRegions(str, 1); + } + + @Test + public void testMethodDeclarationFolding() throws Exception { + String str= """ + package org.example.test; + public class C { + void m() { //here should be an annotation + } + } + """; + assertCodeHasRegions(str, 1); + } + + @Test + public void testIfStatementFolding() throws Exception { + String str= """ + package org.example.test; + public class D { + void x() { //here should be an annotation + if (true) { //here should be an annotation + } + } + } + """; + assertCodeHasRegions(str, 2); + } + + @Test + public void testTryStatementFolding() throws Exception { + String str= """ + package org.example.test; + public class E { + void x() { //here should be an annotation + try { //here should be an annotation + + } catch (Exception e) { //here should be an annotation + + } + } + } + """; + assertCodeHasRegions(str, 3); + } + + @Test + public void testWhileStatementFolding() throws Exception { + String str= """ + package org.example.test; + public class F { + void x() { //here should be an annotation + while (true) { //here should be an annotation + } + } + } + """; + assertCodeHasRegions(str, 2); + } + + @Test + public void testForStatementFolding() throws Exception { + String str= """ + package org.example.test; + public class G { + void x() { //here should be an annotation + for(int i=0;i<1;i++){ //here should be an annotation + } + } + } + """; + assertCodeHasRegions(str, 2); + } + + @Test + public void testEnhancedForStatementFolding() throws Exception { + String str= """ + package org.example.test; + public class H { + void x() { //here should be an annotation + for(String s: new String[0]){ //here should be an annotation + } + } + } + """; + assertCodeHasRegions(str, 2); + } + + @Test + public void testDoStatementFolding() throws Exception { + String str= """ + package org.example.test; + public class I { + void x() { //here should be an annotation + do { //here should be an annotation + } while(false); + } + } + """; + assertCodeHasRegions(str, 2); + } + + @Test + public void testSynchronizedStatementFolding() throws Exception { + String str= """ + package org.example.test; + public class K { + void x() { //here should be an annotation + synchronized(this) { //here should be an annotation + } + } + } + """; + assertCodeHasRegions(str, 2); + } + + @Test + public void testLambdaExpressionFolding() throws Exception { + String str= """ + package org.example.test; + import java.util.function.Supplier; + public class L { + void x() { //here should be an annotation + Supplier s = () -> { //here should be an annotation + return ""; + }; + } + } + """; + assertCodeHasRegions(str, 2); + } + + @Test + public void testAnonymousClassDeclarationFolding() throws Exception { + String str= """ + package org.example.test; + public class M { + Object o = new Object(){ //here should be an annotation + void y() { //here should be an annotation + + } + }; + } + """; + assertCodeHasRegions(str, 2); + } + + @Test + public void testEnumDeclarationFolding() throws Exception { + String str= """ + package org.example.test; + public enum N { //here should be an annotation + A, + B + } + """; + assertCodeHasRegions(str, 1); + } + + @Test + public void testInitializerFolding() throws Exception { + String str= """ + package org.example.test; + public class O { + static { //here should be an annotation + } + } + """; + assertCodeHasRegions(str, 1); + } + + @Test + public void testNestedFolding() throws Exception { + String str= """ + package org.example.test; + public class P { + void x() { //here should be an annotation + if (true) { //here should be an annotation + for(int i=0;i<1;i++){ //here should be an annotation + while(true) { //here should be an annotation + do { //here should be an annotation + } while(false); + } + } + } + } + } + """; + assertCodeHasRegions(str, 5); + } + + @Test + public void testCollapsed() throws Exception { + String code= """ + package org.example.test; + public class P { + void x() { //here should be an annotation + if (true) { //here should be an annotation + } + } + } + """; + ICompilationUnit cu= packageFragment.createCompilationUnit("TestFolding.java", code, true, null); + JavaEditor editor= (JavaEditor) EditorUtility.openInEditor(cu); + JavaSourceViewer viewer= (JavaSourceViewer) editor.getViewer(); + viewer.doOperation(ProjectionViewer.COLLAPSE_ALL); + ProjectionAnnotationModel model= editor.getAdapter(ProjectionAnnotationModel.class); + int foundCollapsed= 0; + + for (Iterator it= model.getAnnotationIterator(); it.hasNext();) { + Annotation annotation= it.next(); + if (annotation instanceof ProjectionAnnotation pa) { + if (pa.isCollapsed()) { + foundCollapsed+= 1; + } + } + } + assertTrue(foundCollapsed == 2); + } + + private void assertCodeHasRegions(String code, int regionsCount) throws Exception { + List regions= getProjectionRangesOfFile(code); + assertEquals(regionsCount, regions.size()); + } +} diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java index b8f64cb15ab..12495a6a841 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/DefaultJavaFoldingPreferenceBlock.java @@ -75,7 +75,7 @@ private OverlayKey[] createKeys() { overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_METHODS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_IMPORTS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOLDING_HEADERS)); - + overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_NEW_FOLDING_ENABLED)); return overlayKeys.toArray(new OverlayKey[overlayKeys.size()]); } @@ -102,6 +102,12 @@ public Control createControl(Composite composite) { addCheckBox(inner, FoldingMessages.DefaultJavaFoldingPreferenceBlock_methods, PreferenceConstants.EDITOR_FOLDING_METHODS, 0); addCheckBox(inner, FoldingMessages.DefaultJavaFoldingPreferenceBlock_imports, PreferenceConstants.EDITOR_FOLDING_IMPORTS, 0); + Label label2= new Label(inner, SWT.LEFT); + label2.setText(""); //$NON-NLS-1$ + Label label1= new Label(inner, SWT.LEFT); + label1.setText(FoldingMessages.DefaultJavaFoldingPreferenceBlock_New_Setting_Title); + + addCheckBox(inner, FoldingMessages.DefaultJavaFoldingPreferenceBlock_New, PreferenceConstants.EDITOR_NEW_FOLDING_ENABLED, 0); return inner; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/FoldingMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/FoldingMessages.java index 92b4ea1637c..2eda049a864 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/FoldingMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/FoldingMessages.java @@ -31,10 +31,11 @@ private FoldingMessages() { public static String DefaultJavaFoldingPreferenceBlock_innerTypes; public static String DefaultJavaFoldingPreferenceBlock_methods; public static String DefaultJavaFoldingPreferenceBlock_imports; + public static String DefaultJavaFoldingPreferenceBlock_New; public static String DefaultJavaFoldingPreferenceBlock_headers; public static String EmptyJavaFoldingPreferenceBlock_emptyCaption; public static String JavaFoldingStructureProviderRegistry_warning_providerNotFound_resetToDefault; - + public static String DefaultJavaFoldingPreferenceBlock_New_Setting_Title; static { NLS.initializeMessages(BUNDLE_NAME, FoldingMessages.class); } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/FoldingMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/FoldingMessages.properties index 3a91f5e6f6f..77fd345f8c5 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/FoldingMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/folding/FoldingMessages.properties @@ -19,7 +19,8 @@ DefaultJavaFoldingPreferenceBlock_innerTypes= Inner &types DefaultJavaFoldingPreferenceBlock_methods= &Members DefaultJavaFoldingPreferenceBlock_imports= &Imports DefaultJavaFoldingPreferenceBlock_headers= &Header Comments - +DefaultJavaFoldingPreferenceBlock_New = &New Folding (Experimental) +DefaultJavaFoldingPreferenceBlock_New_Setting_Title = &New Folding JavaFoldingStructureProviderRegistry_warning_providerNotFound_resetToDefault= The ''{0}'' folding provider could not be found. Resetting to the default folding provider. EmptyJavaFoldingPreferenceBlock_emptyCaption= diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java index 8c32e3d7bf7..c18531ad771 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java @@ -3411,6 +3411,16 @@ private PreferenceConstants() { */ public static final String EDITOR_FOLDING_ENABLED= "editor_folding_enabled"; //$NON-NLS-1$ + /** + * A named preference that controls whether the new or the old folding is used. + *

+ * Value is of type Boolean. + *

+ * + * @since 3.34 + */ + public static final String EDITOR_NEW_FOLDING_ENABLED= "editor_new_folding_enabled"; //$NON-NLS-1$ + /** * A named preference that stores the configured folding provider. *

@@ -4387,6 +4397,8 @@ public static void initializeDefaultValues(IPreferenceStore store) { store.setDefault(EDITOR_JAVA_CODEMINING_DEFAULT_FILTER_FOR_PARAMETER_NAMES, true); store.setDefault(EDITOR_JAVA_CODEMINING_SHOW_PARAMETER_NAME_SINGLE_ARG, true); + store.setDefault(EDITOR_NEW_FOLDING_ENABLED, false); + // Javadoc hover & view JavaElementLinks.initDefaultPreferences(store); } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/folding/DefaultJavaFoldingStructureProvider.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/folding/DefaultJavaFoldingStructureProvider.java index e212f37c39a..dbba06194c1 100755 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/folding/DefaultJavaFoldingStructureProvider.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/folding/DefaultJavaFoldingStructureProvider.java @@ -29,6 +29,8 @@ import org.eclipse.core.runtime.Assert; import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; @@ -68,7 +70,28 @@ import org.eclipse.jdt.core.compiler.IScanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ASTParser; +import org.eclipse.jdt.core.dom.ASTVisitor; +import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; +import org.eclipse.jdt.core.dom.Block; +import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.DoStatement; +import org.eclipse.jdt.core.dom.EnhancedForStatement; +import org.eclipse.jdt.core.dom.EnumDeclaration; +import org.eclipse.jdt.core.dom.ForStatement; +import org.eclipse.jdt.core.dom.IfStatement; +import org.eclipse.jdt.core.dom.ImportDeclaration; +import org.eclipse.jdt.core.dom.Initializer; +import org.eclipse.jdt.core.dom.LambdaExpression; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.dom.Statement; +import org.eclipse.jdt.core.dom.SynchronizedStatement; +import org.eclipse.jdt.core.dom.TryStatement; +import org.eclipse.jdt.core.dom.TypeDeclaration; +import org.eclipse.jdt.core.dom.WhileStatement; import org.eclipse.jdt.ui.PreferenceConstants; @@ -76,7 +99,6 @@ import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; -import org.eclipse.jdt.internal.ui.text.DocumentCharacterIterator; /** * Updates the projection model of a class file or compilation unit. @@ -308,6 +330,314 @@ private static final class Tuple { } } + private class FoldingVisitor extends ASTVisitor { + + private FoldingStructureComputationContext ctx; + + public FoldingVisitor(FoldingStructureComputationContext ctx) { + this.ctx= ctx; + } + + @Override + public boolean visit(CompilationUnit node) { + List imports= node.imports(); + if (imports.size() > 1) { + int start= imports.get(0).getStartPosition(); + ImportDeclaration lastImport= imports.get(imports.size() - 1); + int end= lastImport.getStartPosition() + lastImport.getLength(); + try { + IDocument document= ctx.getDocument(); + int lastImportLine= document.getLineOfOffset(end); + if (lastImportLine + 1 < document.getNumberOfLines()) { + end= document.getLineOffset(lastImportLine + 1); + } else { + end= document.getLength(); + } + } catch (BadLocationException e) { + } + createFoldingRegion(start, end + 1, ctx.collapseMembers()); + } + return super.visit(node); + } + + @Override + public boolean visit(TypeDeclaration node) { + boolean isInnerClass= node.isMemberTypeDeclaration(); + + if (isInnerClass) { + int start= node.getName().getStartPosition(); + int end= node.getStartPosition() + node.getLength(); + createFoldingRegion(start, end, ctx.collapseMembers()); + } + return true; + } + + @Override + public boolean visit(MethodDeclaration node) { + int start= node.getName().getStartPosition(); + int end= node.getStartPosition() + node.getLength(); + createFoldingRegion(start, end, ctx.collapseMembers()); + return true; + } + + @Override + public boolean visit(IfStatement node) { + int start= node.getStartPosition(); + int end= getEndPosition(node.getThenStatement()); + createFoldingRegion(start, end, ctx.collapseMembers()); + node.getThenStatement().accept(this); + if (node.getElseStatement() != null) { + if (node.getElseStatement() instanceof IfStatement) { + Statement elseIfStatement= node.getElseStatement(); + start= findElseKeywordStart(elseIfStatement); + end= getEndPosition(((IfStatement) elseIfStatement).getThenStatement()); + createFoldingRegion(start, end, ctx.collapseMembers()); + node.getElseStatement().accept(this); + } else { + start= findElseKeywordStart(node.getElseStatement()); + end= getEndPosition(node.getElseStatement()); + createFoldingRegion(start, end, ctx.collapseMembers()); + node.getElseStatement().accept(this); + } + } + return false; + } + + @Override + public boolean visit(TryStatement node) { + createFoldingRegionForTryBlock(node); + node.getBody().accept(this); + for (Object obj : node.catchClauses()) { + CatchClause catchClause= (CatchClause) obj; + createFoldingRegionForCatchClause(catchClause); + catchClause.accept(this); + } + if (node.getFinally() != null) { + createFoldingRegionForFinallyBlock(node); + node.getFinally().accept(this); + } + return false; + } + + @Override + public boolean visit(WhileStatement node) { + createFoldingRegionForStatement(node); + node.getBody().accept(this); + return false; + } + + @Override + public boolean visit(ForStatement node) { + createFoldingRegionForStatement(node); + node.getBody().accept(this); + return false; + } + + @Override + public boolean visit(EnhancedForStatement node) { + createFoldingRegionForStatement(node); + node.getBody().accept(this); + return false; + } + + @Override + public boolean visit(DoStatement node) { + createFoldingRegionForStatement(node); + node.getBody().accept(this); + return false; + } + + @Override + public boolean visit(SynchronizedStatement node) { + createFoldingRegion(node, ctx.collapseMembers()); + node.getBody().accept(this); + return false; + } + + @Override + public boolean visit(LambdaExpression node) { + if (node.getBody() instanceof Block) { + createFoldingRegion(node.getBody(), ctx.collapseMembers()); + node.getBody().accept(this); + } + return false; + } + + @Override + public boolean visit(AnonymousClassDeclaration node) { + createFoldingRegion(node, ctx.collapseMembers()); + return true; + } + + @Override + public boolean visit(EnumDeclaration node) { + createFoldingRegion(node, ctx.collapseMembers()); + return true; + } + + @Override + public boolean visit(Initializer node) { + createFoldingRegion(node, ctx.collapseMembers()); + return true; + } + + private void createFoldingRegion(ASTNode node, boolean collapse) { + createFoldingRegion(node.getStartPosition(), node.getStartPosition() + node.getLength(), collapse); + } + + private void createFoldingRegion(int start, int end, boolean collapse) { + if (end > start) { + IRegion region= new Region(start, end - start); + IRegion aligned= alignRegion(region, ctx); + + if (aligned != null && isMultiline(aligned)) { + Position position= new Position(aligned.getOffset(), aligned.getLength()); + JavaProjectionAnnotation annotation= new JavaProjectionAnnotation(collapse, null, false); + ctx.addProjectionRange(annotation, position); + } + } + } + + private boolean isMultiline(IRegion region) { + try { + IDocument document= ctx.getDocument(); + int startLine= document.getLineOfOffset(region.getOffset()); + int endLine= document.getLineOfOffset(region.getOffset() + region.getLength()); + return endLine > startLine; + } catch (BadLocationException e) { + return false; + } + } + + private int findElseKeywordStart(ASTNode node) { + try { + IDocument document= ctx.getDocument(); + int startSearch= node.getParent().getStartPosition(); + int endSearch= node.getStartPosition(); + + String text= document.get(startSearch, endSearch - startSearch); + int index= text.lastIndexOf("else"); //$NON-NLS-1$ + if (index >= 0) { + return startSearch + index; + } + } catch (BadLocationException e) { + e.printStackTrace(); + } + return node.getStartPosition(); + } + + private int getEndPosition(Statement statement) { + if (statement instanceof Block) { + return statement.getStartPosition() + statement.getLength(); + } else { + try { + IDocument document= ctx.getDocument(); + int start= statement.getStartPosition(); + int line= document.getLineOfOffset(start); + return document.getLineOffset(line + 1); + } catch (BadLocationException e) { + e.printStackTrace(); + return statement.getStartPosition() + statement.getLength(); + } + } + } + + private void createFoldingRegionForStatement(ASTNode node) { + int start= node.getStartPosition(); + int length= node.getLength(); + if (!(node instanceof Block)) { + try { + IDocument document= ctx.getDocument(); + int endLine= document.getLineOfOffset(start + length - 1); + if (endLine + 1 < document.getNumberOfLines()) { + String currentIndent= getIndentOfLine(document, endLine); + String nextIndent= getIndentOfLine(document, endLine + 1); + if (nextIndent.length() > currentIndent.length()) { + int nextLineEndOffset= document.getLineOffset(endLine + 2) - 1; + length= nextLineEndOffset - start; + } else { + length= document.getLineOffset(endLine + 1) - start; + } + } else { + length= document.getLength() - start; + } + } catch (BadLocationException e) { + } + } + + IRegion region= new Region(start, length); + IRegion aligned= alignRegion(region, ctx); + + if (aligned != null && isMultiline(aligned)) { + Position position= new Position(aligned.getOffset(), aligned.getLength()); + JavaProjectionAnnotation annotation= new JavaProjectionAnnotation(ctx.collapseMembers(), null, false); + ctx.addProjectionRange(annotation, position); + } + } + + private String getIndentOfLine(IDocument document, int line) throws BadLocationException { + IRegion region= document.getLineInformation(line); + int lineStart= region.getOffset(); + int lineLength= region.getLength(); + + int whiteSpaceEnd= lineStart; + while (whiteSpaceEnd < lineStart + lineLength) { + char c= document.getChar(whiteSpaceEnd); + if (!Character.isWhitespace(c)) { + break; + } + whiteSpaceEnd++; + } + return document.get(lineStart, whiteSpaceEnd - lineStart); + } + + private void createFoldingRegionForTryBlock(TryStatement node) { + int start= node.getStartPosition(); + int end= getEndPosition(node.getBody()); + createFoldingRegion(start, end, ctx.collapseMembers()); + } + + private void createFoldingRegionForCatchClause(CatchClause catchClause) { + int start= catchClause.getStartPosition(); + int end= getEndPosition(catchClause.getBody()); + createFoldingRegion(start, end, ctx.collapseMembers()); + } + + private void createFoldingRegionForFinallyBlock(TryStatement node) { + Block finallyBlock= node.getFinally(); + int start= findFinallyKeywordStart(node); + int end= getEndPosition(finallyBlock); + createFoldingRegion(start, end, ctx.collapseMembers()); + } + + private int findFinallyKeywordStart(TryStatement node) { + try { + IDocument document= ctx.getDocument(); + int startSearch= node.getStartPosition(); + int endSearch= node.getFinally().getStartPosition(); + String text= document.get(startSearch, endSearch - startSearch); + int index= text.lastIndexOf("finally"); //$NON-NLS-1$ + + if (index >= 0) { + return startSearch + index; + } + } catch (BadLocationException e) { + e.printStackTrace(); + } + return node.getFinally().getStartPosition(); + } + } + + private IPropertyChangeListener fPropertyChangeListener = new IPropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent event) { + if (PreferenceConstants.EDITOR_NEW_FOLDING_ENABLED.equals(event.getProperty())) { + fNewFolding = event.getNewValue().equals(Boolean.TRUE); + } + initialize(); + } + }; + /** * Filter for annotations. */ @@ -422,7 +752,6 @@ private boolean shouldIgnoreDelta(CompilationUnit ast, IJavaElementDelta delta) IJavaElement elem= SelectionConverter.getElementAtOffset(ast.getTypeRoot(), new TextSelection(editor.getCachedSelectedRange().x, editor.getCachedSelectedRange().y)); if (!(elem instanceof IImportDeclaration)) return false; - } } catch (JavaModelException e) { return false; // can't compute @@ -469,115 +798,6 @@ private IJavaElementDelta findElement(IJavaElement target, IJavaElementDelta del } } - /** - * Projection position that will return two foldable regions: one folding away - * the region from after the '/**' to the beginning of the content, the other - * from after the first content line until after the comment. - */ - private static final class CommentPosition extends Position implements IProjectionPosition { - CommentPosition(int offset, int length) { - super(offset, length); - } - - /* - * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeFoldingRegions(org.eclipse.jface.text.IDocument) - */ - @Override - public IRegion[] computeProjectionRegions(IDocument document) throws BadLocationException { - DocumentCharacterIterator sequence= new DocumentCharacterIterator(document, offset, offset + length); - int prefixEnd= 0; - int contentStart= findFirstContent(sequence, prefixEnd); - - int firstLine= document.getLineOfOffset(offset + prefixEnd); - int captionLine= document.getLineOfOffset(offset + contentStart); - int lastLine= document.getLineOfOffset(offset + length); - - Assert.isTrue(firstLine <= captionLine, "first folded line is greater than the caption line"); //$NON-NLS-1$ - Assert.isTrue(captionLine <= lastLine, "caption line is greater than the last folded line"); //$NON-NLS-1$ - - IRegion preRegion; - if (firstLine < captionLine) { -// preRegion= new Region(offset + prefixEnd, contentStart - prefixEnd); - int preOffset= document.getLineOffset(firstLine); - IRegion preEndLineInfo= document.getLineInformation(captionLine); - int preEnd= preEndLineInfo.getOffset(); - preRegion= new Region(preOffset, preEnd - preOffset); - } else { - preRegion= null; - } - - if (captionLine < lastLine) { - int postOffset= document.getLineOffset(captionLine + 1); - int postLength= offset + length - postOffset; - if (postLength > 0) { - IRegion postRegion= new Region(postOffset, postLength); - if (preRegion == null) - return new IRegion[] { postRegion }; - return new IRegion[] { preRegion, postRegion }; - } - } - - if (preRegion != null) - return new IRegion[] { preRegion }; - - return null; - } - - /** - * Finds the offset of the first identifier part within content. - * Returns 0 if none is found. - * - * @param content the content to search - * @param prefixEnd the end of the prefix - * @return the first index of a unicode identifier part, or zero if none can - * be found - */ - private int findFirstContent(final CharSequence content, int prefixEnd) { - int lenght= content.length(); - for (int i= prefixEnd; i < lenght; i++) { - if (Character.isUnicodeIdentifierPart(content.charAt(i))) - return i; - } - return 0; - } - -// /** -// * Finds the offset of the first identifier part within content. -// * Returns 0 if none is found. -// * -// * @param content the content to search -// * @return the first index of a unicode identifier part, or zero if none can -// * be found -// */ -// private int findPrefixEnd(final CharSequence content) { -// // return the index after the leading '/*' or '/**' -// int len= content.length(); -// int i= 0; -// while (i < len && isWhiteSpace(content.charAt(i))) -// i++; -// if (len >= i + 2 && content.charAt(i) == '/' && content.charAt(i + 1) == '*') -// if (len >= i + 3 && content.charAt(i + 2) == '*') -// return i + 3; -// else -// return i + 2; -// else -// return i; -// } -// -// private boolean isWhiteSpace(char c) { -// return c == ' ' || c == '\t'; -// } - - /* - * @see org.eclipse.jface.text.source.projection.IProjectionPosition#computeCaptionOffset(org.eclipse.jface.text.IDocument) - */ - @Override - public int computeCaptionOffset(IDocument document) throws BadLocationException { - DocumentCharacterIterator sequence= new DocumentCharacterIterator(document, offset, offset + length); - return findFirstContent(sequence, 0); - } - } - /** * Projection position that will return two foldable regions: one folding away * the lines before the one containing the simple name of the java element, one @@ -650,10 +870,8 @@ public IRegion[] computeProjectionRegions(IDocument document) throws BadLocation return new IRegion[] { preRegion, postRegion }; } } - if (preRegion != null) return new IRegion[] { preRegion }; - return null; } @@ -671,7 +889,6 @@ public int computeCaptionOffset(IDocument document) throws BadLocationException } catch (JavaModelException e) { // ignore and use default } - return nameStart - offset; } @@ -733,6 +950,7 @@ public void projectionDisabled() { private boolean fCollapseInnerTypes= true; private boolean fCollapseMembers= false; private boolean fCollapseHeaderComments= true; + private boolean fNewFolding; /* filters */ /** Member filter, matches nested members (but not top-level types). */ @@ -778,6 +996,8 @@ public void install(ITextEditor editor, ProjectionViewer viewer) { if (editor instanceof JavaEditor) { fProjectionListener= new ProjectionListener(viewer); fEditor= (JavaEditor)editor; + IPreferenceStore store = JavaPlugin.getDefault().getPreferenceStore(); + store.addPropertyChangeListener(fPropertyChangeListener); } } @@ -801,6 +1021,10 @@ private void internalUninstall() { fProjectionListener.dispose(); fProjectionListener= null; fEditor= null; + IPreferenceStore store = JavaPlugin.getDefault().getPreferenceStore(); + if (store != null && fPropertyChangeListener != null) { + store.removePropertyChangeListener(fPropertyChangeListener); + } } } @@ -872,7 +1096,6 @@ private FoldingStructureComputationContext createInitialContext() { fInput= getInputElement(); if (fInput == null) return null; - return createContext(true); } @@ -889,7 +1112,6 @@ private FoldingStructureComputationContext createContext(boolean allowCollapse) IScanner scanner= null; if (fUpdatingCount == 1) scanner= fSharedScanner; // reuse scanner - return new FoldingStructureComputationContext(doc, model, allowCollapse, scanner); } @@ -900,12 +1122,13 @@ private IJavaElement getInputElement() { } private void initializePreferences() { - IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); - fCollapseInnerTypes= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_INNERTYPES); - fCollapseImportContainer= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_IMPORTS); - fCollapseJavadoc= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_JAVADOC); - fCollapseMembers= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_METHODS); - fCollapseHeaderComments= store.getBoolean(PreferenceConstants.EDITOR_FOLDING_HEADERS); + IPreferenceStore store = JavaPlugin.getDefault().getPreferenceStore(); + fCollapseInnerTypes = store.getBoolean(PreferenceConstants.EDITOR_FOLDING_INNERTYPES); + fCollapseImportContainer = store.getBoolean(PreferenceConstants.EDITOR_FOLDING_IMPORTS); + fCollapseJavadoc = store.getBoolean(PreferenceConstants.EDITOR_FOLDING_JAVADOC); + fCollapseMembers = store.getBoolean(PreferenceConstants.EDITOR_FOLDING_METHODS); + fCollapseHeaderComments = store.getBoolean(PreferenceConstants.EDITOR_FOLDING_HEADERS); + fNewFolding = store.getBoolean(PreferenceConstants.EDITOR_NEW_FOLDING_ENABLED); } private void update(FoldingStructureComputationContext ctx) { @@ -935,7 +1158,7 @@ private void update(FoldingStructureComputationContext ctx) { * position update and keep the old range, in order to keep the folding structure * stable. */ - boolean isMalformedAnonymousType= newPosition.getOffset() == 0 && element.getElementType() == IJavaElement.TYPE && isInnerType((IType) element); + boolean isMalformedAnonymousType= newPosition.getOffset() == 0 && element != null && element.getElementType() == IJavaElement.TYPE && isInnerType((IType) element); List annotations= oldStructure.get(element); if (annotations == null) { if (!isMalformedAnonymousType) @@ -990,6 +1213,106 @@ private void update(FoldingStructureComputationContext ctx) { } private void computeFoldingStructure(FoldingStructureComputationContext ctx) { + if (fNewFolding && fInput instanceof ICompilationUnit) { + processCompilationUnit((ICompilationUnit) fInput, ctx); + processComments(ctx); + } else { + processSourceReference(ctx); + } + } + + private void processCompilationUnit(ICompilationUnit unit, FoldingStructureComputationContext ctx) { + try { + String source = unit.getSource(); + if (source == null) return; + + ctx.getScanner().setSource(source.toCharArray()); + ASTParser parser = ASTParser.newParser(AST.getJLSLatest()); + parser.setBindingsRecovery(true); + parser.setStatementsRecovery(true); + parser.setKind(ASTParser.K_COMPILATION_UNIT); + parser.setResolveBindings(true); + parser.setUnitName(unit.getElementName()); + parser.setProject(unit.getJavaProject()); + parser.setSource(unit); + Map options = unit.getJavaProject().getOptions(true); + options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_23); + options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_23); + options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_23); + options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); + parser.setCompilerOptions(options); + + CompilationUnit ast = (CompilationUnit) parser.createAST(null); + ast.accept(new FoldingVisitor(ctx)); + } catch (JavaModelException | IllegalStateException e) { + e.printStackTrace(); + } + } + + private void processComments(FoldingStructureComputationContext ctx) { + try { + IDocument document = ctx.getDocument(); + String source = document.get(); + IScanner scanner = ctx.getScanner(); + scanner.setSource(source.toCharArray()); + scanner.resetTo(0, source.length() - 1); + + int token; + while ((token = scanner.getNextToken()) != ITerminalSymbols.TokenNameEOF) { + if (token == ITerminalSymbols.TokenNameCOMMENT_BLOCK || token == ITerminalSymbols.TokenNameCOMMENT_JAVADOC) { + int start = scanner.getCurrentTokenStartPosition(); + int end = scanner.getCurrentTokenEndPosition() + 1; + try { + int endLine = document.getLineOfOffset(end); + int lineOffset = document.getLineOffset(endLine); + int lineLength = document.getLineLength(endLine); + String lineText = document.get(lineOffset, lineLength); + int commentEndInLine = end - lineOffset; + String afterComment = lineText.substring(commentEndInLine); + + if (afterComment.trim().length() > 0) { + end = lineOffset; + } else { + if (endLine + 1 < document.getNumberOfLines()) { + end = document.getLineOffset(endLine + 1); + } else { + end = document.getLength(); + } + } + } catch (BadLocationException e) { + e.printStackTrace(); + } + + IRegion region = new Region(start, end - start); + IRegion aligned = alignRegion(region, ctx); + + if (aligned != null && isMultiline(aligned, ctx)) { + Position position = createCommentPosition(aligned); + JavaProjectionAnnotation annotation = new JavaProjectionAnnotation(ctx.collapseJavadoc(), null, true); + ctx.addProjectionRange(annotation, position); + } + } + } + } catch (InvalidInputException e) { + e.printStackTrace(); + } + } + + + private boolean isMultiline(IRegion region, FoldingStructureComputationContext ctx) { + try { + IDocument document = ctx.getDocument(); + int startLine = document.getLineOfOffset(region.getOffset()); + int endLine = document.getLineOfOffset(region.getOffset() + region.getLength() - 1); + return endLine > startLine; + } catch (BadLocationException e) { + e.printStackTrace(); + return false; + } + } + + + private void processSourceReference(FoldingStructureComputationContext ctx) { IParent parent= (IParent) fInput; try { if (!(fInput instanceof ISourceReference)) @@ -1004,6 +1327,54 @@ private void computeFoldingStructure(FoldingStructureComputationContext ctx) { } } + /** + * Aligns region to start and end at a line offset. The region's start is + * decreased to the next line offset, and the end offset increased to the next line start or the + * end of the document. null is returned if region is + * null itself or does not comprise at least one line delimiter, as a single line + * cannot be folded. + * + * @param region the region to align, may be null + * @param ctx the folding context + * @return a region equal or greater than region that is aligned with line + * offsets, null if the region is too small to be foldable (e.g. covers + * only one line) + */ + protected IRegion alignRegion(IRegion region, FoldingStructureComputationContext ctx) { + if (region == null) { + return null; + } + + IDocument document = ctx.getDocument(); + + try { + int start= document.getLineOfOffset(region.getOffset()); + int end= document.getLineOfOffset(region.getOffset() + region.getLength() - 1); + if (start >= end) + return null; + + int offset = document.getLineOffset(start); + int endOffset = document.getLineOffset(end); + + return new Region(offset, endOffset - offset); + } catch (BadLocationException e) { + e.printStackTrace(); + return null; + } + } + + /** + * Creates a comment folding position from an + * {@link #alignRegion(IRegion, DefaultJavaFoldingStructureProvider.FoldingStructureComputationContext) aligned} + * region. + * + * @param aligned an aligned region + * @return a folding position corresponding to aligned + */ + protected Position createCommentPosition(IRegion aligned) { + return new Position(aligned.getOffset(), aligned.getLength()); + } + private void computeFoldingStructure(IJavaElement[] elements, FoldingStructureComputationContext ctx) throws JavaModelException { for (IJavaElement element : elements) { computeFoldingStructure(element, ctx); @@ -1178,7 +1549,6 @@ protected final IRegion[] computeProjectionRanges(ISourceReference reference, Fo return result; } catch (JavaModelException | InvalidInputException e) { } - return new IRegion[0]; } @@ -1234,18 +1604,6 @@ private IRegion computeHeaderComment(FoldingStructureComputationContext ctx) thr return null; } - /** - * Creates a comment folding position from an - * {@link #alignRegion(IRegion, DefaultJavaFoldingStructureProvider.FoldingStructureComputationContext) aligned} - * region. - * - * @param aligned an aligned region - * @return a folding position corresponding to aligned - */ - protected final Position createCommentPosition(IRegion aligned) { - return new CommentPosition(aligned.getOffset(), aligned.getLength()); - } - /** * Creates a folding position that remembers its member from an * {@link #alignRegion(IRegion, DefaultJavaFoldingStructureProvider.FoldingStructureComputationContext) aligned} @@ -1259,47 +1617,6 @@ protected final Position createMemberPosition(IRegion aligned, IMember member) { return new JavaElementPosition(aligned.getOffset(), aligned.getLength(), member); } - /** - * Aligns region to start and end at a line offset. The region's start is - * decreased to the next line offset, and the end offset increased to the next line start or the - * end of the document. null is returned if region is - * null itself or does not comprise at least one line delimiter, as a single line - * cannot be folded. - * - * @param region the region to align, may be null - * @param ctx the folding context - * @return a region equal or greater than region that is aligned with line - * offsets, null if the region is too small to be foldable (e.g. covers - * only one line) - */ - protected final IRegion alignRegion(IRegion region, FoldingStructureComputationContext ctx) { - if (region == null) - return null; - - IDocument document= ctx.getDocument(); - - try { - - int start= document.getLineOfOffset(region.getOffset()); - int end= document.getLineOfOffset(region.getOffset() + region.getLength()); - if (start >= end) - return null; - - int offset= document.getLineOffset(start); - int endOffset; - if (document.getNumberOfLines() > end + 1) - endOffset= document.getLineOffset(end + 1); - else - endOffset= document.getLineOffset(end) + document.getLineLength(end); - - return new Region(offset, endOffset - offset); - - } catch (BadLocationException x) { - // concurrent modification - return null; - } - } - private ProjectionAnnotationModel getModel() { return fEditor.getAdapter(ProjectionAnnotationModel.class); } @@ -1513,4 +1830,4 @@ private void modifyFiltered(Filter filter, boolean expand) { model.modifyAnnotations(null, null, modified.toArray(new Annotation[modified.size()])); } -} +} \ No newline at end of file