Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 2004, 2006 John-Mason P. Shackelford and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html Contributors: John-Mason P. Shackelford - initial API and implementation /
 
 package org.eclipse.ant.internal.ui.editor.formatter;
 
 import java.util.List;
 
Utility class for using the ant code formatter in contexts where an IDocument containing the text to format is not readily available.
 
 public class XmlFormatter {
 
 	private static final String POS_CATEGORY"tempAntFormatterCategory"//$NON-NLS-1$
 	
    
Format the text using the ant code formatter.

Parameters:
text The text to format. Must be a non-null value.
prefs Preferences to use for this format operation. If null, the preferences currently set in the plug-in's preferences store are used.
Returns:
The formatted text.
 
     public static String format(String textFormattingPreferences prefs) {
         
       return format(textprefs, -1);
     }
     
     private static String format(String textFormattingPreferences prefsint indent) {
     	 Assert.isNotNull(text);
          
          FormattingPreferences applyPrefs;
          if(prefs == null) {
              applyPrefs = new FormattingPreferences();
          } else {
              applyPrefs = prefs;
          }
          
          IDocument doc = new Document();
          doc.set(text);
          new AntDocumentSetupParticipant().setup(doc);
 
          format(applyPrefsdocindent);
 
          return doc.get();
     }
 
 	private static void format(FormattingPreferences prefsIDocument docint indent) {
                 .,
                 .);
 
         formatter.setMasterStrategy(new XmlDocumentFormattingStrategy(prefsindent));
         formatter.setSlaveStrategy(new XmlElementFormattingStrategy(prefs),
                 .);
         formatter.format(docnew Region(0, doc.getLength()));
 	}

Format the text using the ant code formatter using the preferences settings in the plug-in preference store.

Parameters:
text The text to format. Must be a non-null value.
Returns:
The formatted text.
 
     public static String format(String text) {
         return format(text,null);
    }
    
    public static void format(TemplateBuffer templateBufferAntContext antContextFormattingPreferences prefs) {	
    	String templateStringtemplateBuffer.getString();
    	IDocument fullDocumentnew Document(antContext.getDocument().get());
    	
    	int completionOffsetantContext.getCompletionOffset();
    	try {
    		//trim any starting whitespace
			IRegion lineRegionfullDocument.getLineInformationOfOffset(completionOffset);
			String lineStringfullDocument.get(lineRegion.getOffset(), lineRegion.getLength());
			lineStringtrimBegin(lineString);
			fullDocument.replace(lineRegion.getOffset(), lineRegion.getLength(), lineString);
catch (BadLocationException e1) {
			return;
		}
    	TemplateVariable[] variablestemplateBuffer.getVariables();
		int[] offsetsvariablesToOffsets(variablescompletionOffset);
		IDocument origTemplateDocnew Document(fullDocument.get());
		try {
			origTemplateDoc.replace(completionOffsetantContext.getCompletionLength(), templateString);
catch (BadLocationException e) {
			return// don't format if the document has changed
		}
    	IDocument templateDocumentcreateDocument(origTemplateDoc.get(), createPositions(offsets));
    	
    	String leadingTextgetLeadingText(fullDocumentantContext.getAntModel(), completionOffset);
    	String newTemplateStringleadingText + templateString;
    	int indent= XmlDocumentFormatter.computeIndent(leadingTextprefs.getTabWidth());
    	
    	newTemplateStringformat(newTemplateStringprefsindent);
    	
    	try {
    		templateDocument.replace(completionOffsettemplateString.length(), newTemplateString);
catch (BadLocationException e) {
			return;
		}
		Position[] positionsnull;
		try {
			positionstemplateDocument.getPositions();
		}
    	//offsetsToVariables(offsets, variables, completionOffset);
		positionsToVariables(positionsvariablescompletionOffset);
    	templateBuffer.setContent(newTemplateStringvariables);
    }
    
    private static void positionsToVariables(Position[] positionsTemplateVariable[] variablesint start) {
		for (int i= 0; i != variables.lengthi++) {
		    TemplateVariable variablevariables[i];
		    
			int[] offsetsnew int[variable.getOffsets().length];
			for (int j= 0; j != offsets.lengthj++) {
				offsets[j]= positions[j].getOffset() - start;
			}
		 	variable.setOffsets(offsets);   
		}
	}	
    private static Document createDocument(String stringPosition[] positionsthrows IllegalArgumentException {
		Document docnew Document(string);
		try {
			if (positions != null) {
					protected boolean notDeleted() {
							. + // deleted positions: set to end of remove
							return false;
						}
						return true;
					}
				});
				for (int i= 0; i < positions.lengthi++) {
					try {
						doc.addPosition(positions[i]);
catch (BadLocationException e) {
						throw new IllegalArgumentException("Position outside of string. offset: " + positions[i]. + ", length: " + positions[i]. + ", string size: " + string.length());   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
					}
				}
			}
catch (BadPositionCategoryException cannotHappen) {
			// can not happen: category is correctly set up
		}
		return doc;
	}
    
    public static String trimBegin(String toBeTrimmed) {
		int i= 0;
		while ((i != toBeTrimmed.length()) && Character.isWhitespace(toBeTrimmed.charAt(i))) {
			i++;
		}
		return toBeTrimmed.substring(i);
	}
    
    private static int[] variablesToOffsets(TemplateVariable[] variablesint start) {
		List listnew ArrayList();
		for (int i= 0; i != variables.lengthi++) {
		    int[] offsetsvariables[i].getOffsets();
		    for (int j= 0; j != offsets.lengthj++) {
				list.add(new Integer(offsets[j]));
		    }
		}
		int[] offsetsnew int[list.size()];
		for (int i= 0; i != offsets.lengthi++) {
			offsets[i]= ((Integerlist.get(i)).intValue() + start;
		}
		Arrays.sort(offsets);
		return offsets;	    
	}

Returns the indentation level at the position of code completion.
	private static String getLeadingText(IDocument documentIAntModel modelint completionOffset) {
		AntProjectNode projectmodel.getProjectNode(false);
		if (project == null) {
			return ""//$NON-NLS-1$
		}
		AntElementNode nodeproject.getNode(completionOffset);// - fAccumulatedChange);
		if (node == null) {
			return ""//$NON-NLS-1$
		}
		buf.append(XmlDocumentFormatter.getLeadingWhitespace(node.getOffset(), document));
		buf.append(XmlDocumentFormatter.createIndent());
		return buf.toString();
	}
	 private static Position[] createPositions(int[] positions) {
    	Position[] pnull;
		if (positions != null) {
			pnew Position[positions.length];
			for (int i= 0; i < positions.lengthi++) {
				p[i]= new Position(positions[i], 0);
			}
		}
		return p;
    }
New to GrepCode? Check out our FAQ X