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..65f2bbfd633 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/folding/FoldingTest.java @@ -0,0 +1,339 @@ +package org.eclipse.jdt.ui.tests.folding; + +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.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.ui.PartInitException; + +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.core.JavaModelException; + +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 = org.eclipse.jdt.testplugin.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 { + org.eclipse.jdt.testplugin.JavaProjectHelper.delete(jProject); + } + + @Test + public void testCompilationUnitFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class A { + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.isEmpty()); + } + + @Test + public void testTypeDeclarationFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class B { + class Inner { + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 1); + } + + @Test + public void testMethodDeclarationFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class C { + void m() { + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 1); + } + + @Test + public void testIfStatementFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class D { + void x() { + if (true) { + } + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 2); + } + + @Test + public void testTryStatementFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class E { + void x() { + try { + + } catch (Exception e) { + + } + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 3); + } + + @Test + public void testWhileStatementFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class F { + void x() { + while (true) { + } + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 2); + } + + @Test + public void testForStatementFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class G { + void x() { + for(int i=0;i<1;i++){ + } + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 2); + } + + @Test + public void testEnhancedForStatementFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class H { + void x() { + for(String s: new String[0]){ + } + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 2); + } + + @Test + public void testDoStatementFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class I { + void x() { + do { + } while(false); + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 2); + } + + @Test + public void testSynchronizedStatementFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class K { + void x() { + synchronized(this) { + } + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 2); + } + + @Test + public void testLambdaExpressionFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + import java.util.function.Supplier; + public class L { + void x() { + Supplier s = () -> { + return ""; + }; + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 2); + } + + @Test + public void testAnonymousClassDeclarationFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class M { + Object o = new Object(){ + void y() { + + } + }; + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 2); + } + + @Test + public void testEnumDeclarationFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public enum N { + A, + B + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 1); + } + + @Test + public void testInitializerFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class O { + static { + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 1); + } + + @Test + public void testNestedFolding() throws JavaModelException, PartInitException { + String str = """ + package org.example.test; + public class P { + void x() { + if (true) { + for(int i=0;i<1;i++){ + while(true) { + do { + } while(false); + } + } + } + } + } + """; + List regions = getProjectionRangesOfFile(str); + assertTrue(regions.size() >= 4); + } + + @Test + public void testCollapsed() throws JavaModelException, PartInitException { + String code = """ + package org.example.test; + public class P { + void x() { + if (true) { + } + } + } + """; + 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 List getProjectionRangesOfFile(String str) throws JavaModelException, PartInitException { + 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; + } +} 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..4e34bd6e268 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,356 @@ 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.isEmpty() && 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) { + } + + IRegion region = new Region(start, end - start); + IRegion aligned = alignRegion(region, ctx); + + if (aligned != null) { + Position position = new Position(aligned.getOffset(), aligned.getLength()); + JavaProjectionAnnotation annotation = new JavaProjectionAnnotation(ctx.collapseImportContainer(), null, false); + ctx.addProjectionRange(annotation, position); + } + } + return super.visit(node); + } + + @Override + public boolean visit(TypeDeclaration node) { + boolean isInnerClass = node.isMemberTypeDeclaration(); + + if (isInnerClass) { + int start = node.getName().getStartPosition(); + int length = (node.getStartPosition() + node.getLength()) - start; + + if (length > 0) { + 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.collapseInnerTypes(), null, false); + ctx.addProjectionRange(annotation, position); + } + } + } + return true; + } + + @Override + public boolean visit(MethodDeclaration node) { + int start = node.getName().getStartPosition(); + int length = (node.getStartPosition() + node.getLength()) - start; + + if (length > 0) { + 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); + } + } + return true; + } + + @Override + public boolean visit(IfStatement node) { + createFoldingRegionForIfPart(node); + node.getThenStatement().accept(this); + if (node.getElseStatement() != null) { + if (node.getElseStatement() instanceof IfStatement) { + createFoldingRegionForElseIfPart(node.getElseStatement()); + node.getElseStatement().accept(this); + } else { + createFoldingRegionForElsePart(node); + 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 void createFoldingRegionForIfPart(IfStatement node) { + int start = node.getStartPosition(); + int end = getEndPosition(node.getThenStatement()); + createFoldingRegion(start, end, ctx.collapseMembers()); + } + + private void createFoldingRegionForElseIfPart(Statement elseIfStatement) { + int start = findElseKeywordStart(elseIfStatement); + int end = getEndPosition(((IfStatement) elseIfStatement).getThenStatement()); + createFoldingRegion(start, end, ctx.collapseMembers()); + } + + private void createFoldingRegionForElsePart(IfStatement node) { + int start = findElseKeywordStart(node.getElseStatement()); + int end = getEndPosition(node.getElseStatement()); + createFoldingRegion(start, end, ctx.collapseMembers()); + } + + 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 +794,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 +840,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 +912,8 @@ public IRegion[] computeProjectionRegions(IDocument document) throws BadLocation return new IRegion[] { preRegion, postRegion }; } } - if (preRegion != null) return new IRegion[] { preRegion }; - return null; } @@ -671,7 +931,6 @@ public int computeCaptionOffset(IDocument document) throws BadLocationException } catch (JavaModelException e) { // ignore and use default } - return nameStart - offset; } @@ -733,6 +992,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 +1038,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 +1063,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 +1138,6 @@ private FoldingStructureComputationContext createInitialContext() { fInput= getInputElement(); if (fInput == null) return null; - return createContext(true); } @@ -889,7 +1154,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 +1164,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 +1200,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 +1255,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 +1369,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); @@ -1015,6 +1428,7 @@ private void computeFoldingStructure(IJavaElement[] elements, FoldingStructureCo } } + /** * Computes the folding structure for a given {@link IJavaElement java element}. Computed * projection annotations are @@ -1178,7 +1592,6 @@ protected final IRegion[] computeProjectionRanges(ISourceReference reference, Fo return result; } catch (JavaModelException | InvalidInputException e) { } - return new IRegion[0]; } @@ -1234,18 +1647,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 +1660,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 +1873,4 @@ private void modifyFiltered(Filter filter, boolean expand) { model.modifyAnnotations(null, null, modified.toArray(new Annotation[modified.size()])); } -} +} \ No newline at end of file