1 11 package org.eclipse.jdt.internal.formatter.comment; 12 13 import java.util.Map ; 14 15 import org.eclipse.text.edits.TextEdit; 16 17 import org.eclipse.core.runtime.Assert; 18 import org.eclipse.jface.text.BadLocationException; 19 import org.eclipse.jface.text.BadPositionCategoryException; 20 import org.eclipse.jface.text.DefaultPositionUpdater; 21 import org.eclipse.jface.text.Document; 22 import org.eclipse.jface.text.Position; 23 24 import org.eclipse.jdt.core.ToolFactory; 25 26 import org.eclipse.jdt.internal.core.util.Util; 27 28 33 public class CommentFormatterUtil { 34 35 41 public static String evaluateFormatterEdit(String string, TextEdit edit, Position[] positions) { 42 try { 43 Document doc= createDocument(string, positions); 44 edit.apply(doc, 0); 45 if (positions != null) { 46 for (int i= 0; i < positions.length; i++) { 47 Assert.isTrue(!positions[i].isDeleted, "Position got deleted"); } 49 } 50 return doc.get(); 51 } catch (BadLocationException e) { 52 log(e); Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); } 55 return null; 56 } 57 58 66 public static TextEdit format2(int kind, String string, int indentationLevel, String lineSeparator, Map options) { 67 int length= string.length(); 68 if (0 < 0 || length < 0 || 0 + length > string.length()) { 69 throw new IllegalArgumentException ("offset or length outside of string. offset: " + 0 + ", length: " + length + ", string size: " + string.length()); } 71 return ToolFactory.createCodeFormatter(options).format(kind, string, 0, length, indentationLevel, lineSeparator); 72 } 73 74 83 private static Document createDocument(String content, Position[] positions) throws IllegalArgumentException { 84 Document doc= new Document(content); 85 try { 86 if (positions != null) { 87 final String POS_CATEGORY= "myCategory"; 89 doc.addPositionCategory(POS_CATEGORY); 90 doc.addPositionUpdater(new DefaultPositionUpdater(POS_CATEGORY) { 91 protected boolean notDeleted() { 92 if (fOffset < fPosition.offset && (fPosition.offset + fPosition.length < fOffset + fLength)) { 93 fPosition.offset= fOffset + fLength; return false; 95 } 96 return true; 97 } 98 }); 99 for (int i= 0; i < positions.length; i++) { 100 try { 101 doc.addPosition(POS_CATEGORY, positions[i]); 102 } catch (BadLocationException e) { 103 throw new IllegalArgumentException ("Position outside of string. offset: " + positions[i].offset + ", length: " + positions[i].length + ", string size: " + content.length()); } 105 } 106 } 107 } catch (BadPositionCategoryException cannotHappen) { 108 } 110 return doc; 111 } 112 113 119 public static void log(Throwable t) { 120 Util.log(t, "Exception occured while formatting comments"); } 122 } 123 | Popular Tags |