1 12 13 package org.eclipse.ant.internal.ui.editor.formatter; 14 15 import java.util.LinkedList ; 16 17 import org.eclipse.core.runtime.Assert; 18 import org.eclipse.jface.text.BadLocationException; 19 import org.eclipse.jface.text.IDocument; 20 import org.eclipse.jface.text.IRegion; 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 public class XmlElementFormattingStrategy extends ContextBasedFormattingStrategy { 28 29 30 private final FormattingPreferences prefs; 31 32 33 private final LinkedList fDocuments= new LinkedList (); 34 35 private final LinkedList fPartitions= new LinkedList (); 36 37 public XmlElementFormattingStrategy() { 38 this.prefs = new FormattingPreferences(); 39 } 40 41 public XmlElementFormattingStrategy(FormattingPreferences prefs) { 42 Assert.isNotNull(prefs); 43 this.prefs=prefs; 44 } 45 46 51 public void format() { 52 53 super.format(); 54 55 final IDocument document= (IDocument)fDocuments.removeFirst(); 56 final TypedPosition partition= (TypedPosition)fPartitions.removeFirst(); 57 58 if (document == null || partition == null) { 59 return; 60 } 61 62 try { 63 String formatted = formatElement(document, partition); 64 String partitionText = document.get(partition.getOffset(), 65 partition.getLength()); 66 67 if (formatted != null && !formatted.equals(partitionText)) { 68 document.replace(partition.getOffset(), partition.getLength(), 69 formatted); 70 } 71 72 } catch (BadLocationException e) { 73 } 74 } 75 76 private String formatElement(IDocument document, TypedPosition partition) 77 throws BadLocationException { 78 79 String partitionText = document.get(partition.getOffset(), partition.getLength()); 80 81 IRegion line = document.getLineInformationOfOffset(partition.getOffset()); 82 83 int indentLength = partition.getOffset() - line.getOffset(); 84 String lineDelimiter= document.getLineDelimiter(document.getLineOfOffset(line.getOffset())); 85 if (lineDelimiter == null) { 86 lineDelimiter= TextUtilities.getDefaultLineDelimiter(document); 87 } 88 return XmlTagFormatter.format(partitionText, prefs, document.get(line.getOffset(), indentLength), lineDelimiter); 89 90 } 91 92 95 public void formatterStarts(final IFormattingContext context) { 96 super.formatterStarts(context); 97 98 fPartitions.addLast(context.getProperty(FormattingContextProperties.CONTEXT_PARTITION)); 99 fDocuments.addLast(context.getProperty(FormattingContextProperties.CONTEXT_MEDIUM)); 100 } 101 102 105 public void formatterStops() { 106 super.formatterStops(); 107 108 fPartitions.clear(); 109 fDocuments.clear(); 110 } 111 } | Popular Tags |