1 11 package org.eclipse.jdt.internal.ui.text.java; 12 13 import java.util.LinkedList ; 14 import java.util.Map ; 15 16 import org.eclipse.text.edits.MalformedTreeException; 17 import org.eclipse.text.edits.TextEdit; 18 19 import org.eclipse.jface.text.BadLocationException; 20 import org.eclipse.jface.text.IDocument; 21 import org.eclipse.jface.text.TextUtilities; 22 import org.eclipse.jface.text.TypedPosition; 23 import org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy; 24 import org.eclipse.jface.text.formatter.FormattingContextProperties; 25 import org.eclipse.jface.text.formatter.IFormattingContext; 26 27 import org.eclipse.jdt.core.formatter.CodeFormatter; 28 29 import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; 30 import org.eclipse.jdt.internal.ui.JavaPlugin; 31 32 37 public class JavaFormattingStrategy extends ContextBasedFormattingStrategy { 38 39 40 private final LinkedList fDocuments= new LinkedList (); 41 42 private final LinkedList fPartitions= new LinkedList (); 43 44 47 public JavaFormattingStrategy() { 48 super(); 49 } 50 51 54 public void format() { 55 super.format(); 56 57 final IDocument document= (IDocument)fDocuments.removeFirst(); 58 final TypedPosition partition= (TypedPosition)fPartitions.removeFirst(); 59 60 if (document != null && partition != null) { 61 Map partitioners= null; 62 try { 63 64 final TextEdit edit= CodeFormatterUtil.reformat(CodeFormatter.K_COMPILATION_UNIT, document.get(), partition.getOffset(), partition.getLength(), 0, TextUtilities.getDefaultLineDelimiter(document), getPreferences()); 65 if (edit != null) { 66 if (edit.getChildrenSize() > 20) 67 partitioners= TextUtilities.removeDocumentPartitioners(document); 68 69 edit.apply(document); 70 } 71 72 } catch (MalformedTreeException exception) { 73 JavaPlugin.log(exception); 74 } catch (BadLocationException exception) { 75 JavaPlugin.log(exception); 77 } finally { 78 if (partitioners != null) 79 TextUtilities.addDocumentPartitioners(document, partitioners); 80 } 81 } 82 } 83 84 87 public void formatterStarts(final IFormattingContext context) { 88 super.formatterStarts(context); 89 90 fPartitions.addLast(context.getProperty(FormattingContextProperties.CONTEXT_PARTITION)); 91 fDocuments.addLast(context.getProperty(FormattingContextProperties.CONTEXT_MEDIUM)); 92 } 93 94 97 public void formatterStops() { 98 super.formatterStops(); 99 100 fPartitions.clear(); 101 fDocuments.clear(); 102 } 103 } 104 | Popular Tags |