KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > corext > util > Strings


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.jdt.internal.corext.util;
12
13 import org.eclipse.core.runtime.Assert;
14
15 import org.eclipse.jface.action.LegacyActionTools;
16
17 import org.eclipse.jface.text.BadLocationException;
18 import org.eclipse.jface.text.DefaultLineTracker;
19 import org.eclipse.jface.text.ILineTracker;
20 import org.eclipse.jface.text.IRegion;
21
22 import org.eclipse.jdt.core.IJavaProject;
23 import org.eclipse.jdt.core.formatter.IndentManipulation;
24
25
26 /**
27  * Helper class to provide String manipulation functions not available in standard JDK.
28  */

29 public class Strings {
30     
31     private Strings(){}
32     
33     /**
34      * tests if a char is lower case. Fix for 26529
35      */

36     public static boolean isLowerCase(char ch) {
37         return Character.toLowerCase(ch) == ch;
38     }
39     
40     public static boolean startsWithIgnoreCase(String JavaDoc text, String JavaDoc prefix) {
41         int textLength= text.length();
42         int prefixLength= prefix.length();
43         if (textLength < prefixLength)
44             return false;
45         for (int i= prefixLength - 1; i >= 0; i--) {
46             if (Character.toLowerCase(prefix.charAt(i)) != Character.toLowerCase(text.charAt(i)))
47                 return false;
48         }
49         return true;
50     }
51
52     public static String JavaDoc removeNewLine(String JavaDoc message) {
53         StringBuffer JavaDoc result= new StringBuffer JavaDoc();
54         int current= 0;
55         int index= message.indexOf('\n', 0);
56         while (index != -1) {
57             result.append(message.substring(current, index));
58             if (current < index && index != 0)
59                 result.append(' ');
60             current= index + 1;
61             index= message.indexOf('\n', current);
62         }
63         result.append(message.substring(current));
64         return result.toString();
65     }
66
67     /**
68      * Converts the given string into an array of lines. The lines
69      * don't contain any line delimiter characters.
70      *
71      * @return the string converted into an array of strings. Returns <code>
72      * null</code> if the input string can't be converted in an array of lines.
73      */

74     public static String JavaDoc[] convertIntoLines(String JavaDoc input) {
75         try {
76             ILineTracker tracker= new DefaultLineTracker();
77             tracker.set(input);
78             int size= tracker.getNumberOfLines();
79             String JavaDoc result[]= new String JavaDoc[size];
80             for (int i= 0; i < size; i++) {
81                 IRegion region= tracker.getLineInformation(i);
82                 int offset= region.getOffset();
83                 result[i]= input.substring(offset, offset + region.getLength());
84             }
85             return result;
86         } catch (BadLocationException e) {
87             return null;
88         }
89     }
90
91     /**
92      * Returns <code>true</code> if the given string only consists of
93      * white spaces according to Java. If the string is empty, <code>true
94      * </code> is returned.
95      *
96      * @return <code>true</code> if the string only consists of white
97      * spaces; otherwise <code>false</code> is returned
98      *
99      * @see java.lang.Character#isWhitespace(char)
100      */

101     public static boolean containsOnlyWhitespaces(String JavaDoc s) {
102         int size= s.length();
103         for (int i= 0; i < size; i++) {
104             if (!Character.isWhitespace(s.charAt(i)))
105                 return false;
106         }
107         return true;
108     }
109     
110     /**
111      * Removes leading tabs and spaces from the given string. If the string
112      * doesn't contain any leading tabs or spaces then the string itself is
113      * returned.
114      */

115     public static String JavaDoc trimLeadingTabsAndSpaces(String JavaDoc line) {
116         int size= line.length();
117         int start= size;
118         for (int i= 0; i < size; i++) {
119             char c= line.charAt(i);
120             if (!IndentManipulation.isIndentChar(c)) {
121                 start= i;
122                 break;
123             }
124         }
125         if (start == 0)
126             return line;
127         else if (start == size)
128             return ""; //$NON-NLS-1$
129
else
130             return line.substring(start);
131     }
132     
133     public static String JavaDoc trimTrailingTabsAndSpaces(String JavaDoc line) {
134         int size= line.length();
135         int end= size;
136         for (int i= size - 1; i >= 0; i--) {
137             char c= line.charAt(i);
138             if (IndentManipulation.isIndentChar(c)) {
139                 end= i;
140             } else {
141                 break;
142             }
143         }
144         if (end == size)
145             return line;
146         else if (end == 0)
147             return ""; //$NON-NLS-1$
148
else
149             return line.substring(0, end);
150     }
151         
152     /**
153      * Returns the indent of the given string in indentation units. Odd spaces
154      * are not counted.
155      *
156      * @param line the text line
157      * @param project the java project from which to get the formatter
158      * preferences, or <code>null</code> for global preferences
159      * @since 3.1
160      */

161     public static int computeIndentUnits(String JavaDoc line, IJavaProject project) {
162         return IndentManipulation.measureIndentUnits(line, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project));
163     }
164     
165     /**
166      * Returns the indent of the given string in indentation units. Odd spaces
167      * are not counted.
168      *
169      * @param line the text line
170      * @param tabWidth the width of the '\t' character in space equivalents
171      * @param indentWidth the width of one indentation unit in space equivalents
172      * @since 3.1
173      */

174     public static int computeIndentUnits(String JavaDoc line, int tabWidth, int indentWidth) {
175         return IndentManipulation.measureIndentUnits(line, tabWidth, indentWidth);
176     }
177     
178     /**
179      * Computes the visual length of the indentation of a
180      * <code>CharSequence</code>, counting a tab character as the size until
181      * the next tab stop and every other whitespace character as one.
182      *
183      * @param line the string to measure the indent of
184      * @param tabSize the visual size of a tab in space equivalents
185      * @return the visual length of the indentation of <code>line</code>
186      * @since 3.1
187      */

188     public static int measureIndentLength(CharSequence JavaDoc line, int tabSize) {
189         return IndentManipulation.measureIndentInSpaces(line, tabSize);
190     }
191
192     /**
193      * Removes the given number of indents from the line. Asserts that the given line
194      * has the requested number of indents. If <code>indentsToRemove <= 0</code>
195      * the line is returned.
196      *
197      * @param project the java project from which to get the formatter
198      * preferences, or <code>null</code> for global preferences
199      * @since 3.1
200      */

201     public static String JavaDoc trimIndent(String JavaDoc line, int indentsToRemove, IJavaProject project) {
202         return IndentManipulation.trimIndent(line, indentsToRemove, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project));
203     }
204     
205     /**
206      * Removes the given number of indents from the line. Asserts that the given line
207      * has the requested number of indents. If <code>indentsToRemove <= 0</code>
208      * the line is returned.
209      *
210      * @since 3.1
211      */

212     public static String JavaDoc trimIndent(String JavaDoc line, int indentsToRemove, int tabWidth, int indentWidth) {
213         return IndentManipulation.trimIndent(line, indentsToRemove, tabWidth, indentWidth);
214     }
215     
216     /**
217      * Removes the common number of indents from all lines. If a line
218      * only consists out of white space it is ignored.
219
220      * @param project the java project from which to get the formatter
221      * preferences, or <code>null</code> for global preferences
222      * @since 3.1
223      */

224     public static void trimIndentation(String JavaDoc[] lines, IJavaProject project) {
225         trimIndentation(lines, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), true);
226     }
227     /**
228      * Removes the common number of indents from all lines. If a line
229      * only consists out of white space it is ignored.
230      *
231      * @since 3.1
232      */

233     public static void trimIndentation(String JavaDoc[] lines, int tabWidth, int indentWidth) {
234         trimIndentation(lines, tabWidth, indentWidth, true);
235     }
236     
237     /**
238      * Removes the common number of indents from all lines. If a line
239      * only consists out of white space it is ignored. If <code>
240      * considerFirstLine</code> is false the first line will be ignored.
241      *
242      * @param project the java project from which to get the formatter
243      * preferences, or <code>null</code> for global preferences
244      * @since 3.1
245      */

246     public static void trimIndentation(String JavaDoc[] lines, IJavaProject project, boolean considerFirstLine) {
247         trimIndentation(lines, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), considerFirstLine);
248     }
249     
250     /**
251      * Removes the common number of indents from all lines. If a line
252      * only consists out of white space it is ignored. If <code>
253      * considerFirstLine</code> is false the first line will be ignored.
254      * @since 3.1
255      */

256     public static void trimIndentation(String JavaDoc[] lines, int tabWidth, int indentWidth, boolean considerFirstLine) {
257         String JavaDoc[] toDo= new String JavaDoc[lines.length];
258         // find indentation common to all lines
259
int minIndent= Integer.MAX_VALUE; // very large
260
for (int i= considerFirstLine ? 0 : 1; i < lines.length; i++) {
261             String JavaDoc line= lines[i];
262             if (containsOnlyWhitespaces(line))
263                 continue;
264             toDo[i]= line;
265             int indent= computeIndentUnits(line, tabWidth, indentWidth);
266             if (indent < minIndent) {
267                 minIndent= indent;
268             }
269         }
270         
271         if (minIndent > 0) {
272             // remove this indent from all lines
273
for (int i= considerFirstLine ? 0 : 1; i < toDo.length; i++) {
274                 String JavaDoc s= toDo[i];
275                 if (s != null)
276                     lines[i]= trimIndent(s, minIndent, tabWidth, indentWidth);
277                 else {
278                     String JavaDoc line= lines[i];
279                     int indent= computeIndentUnits(line, tabWidth, indentWidth);
280                     if (indent > minIndent)
281                         lines[i]= trimIndent(line, minIndent, tabWidth, indentWidth);
282                     else
283                         lines[i]= trimLeadingTabsAndSpaces(line);
284                 }
285             }
286         }
287     }
288         
289     /**
290      * Returns that part of the indentation of <code>line</code> that makes up
291      * a multiple of indentation units.
292      *
293      * @param line the line to scan
294      * @param project the java project from which to get the formatter
295      * preferences, or <code>null</code> for global preferences
296      * @return the indent part of <code>line</code>, but no odd spaces
297      * @since 3.1
298      */

299     public static String JavaDoc getIndentString(String JavaDoc line, IJavaProject project) {
300         return IndentManipulation.extractIndentString(line, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project));
301     }
302     
303     /**
304      * Returns that part of the indentation of <code>line</code> that makes up
305      * a multiple of indentation units.
306      *
307      * @param line the line to scan
308      * @param tabWidth the size of one tab in space equivalents
309      * @param indentWidth the size of the indent in space equivalents
310      * @return the indent part of <code>line</code>, but no odd spaces
311      * @since 3.1
312      */

313     public static String JavaDoc getIndentString(String JavaDoc line, int tabWidth, int indentWidth) {
314         return IndentManipulation.extractIndentString(line, tabWidth, indentWidth);
315     }
316         
317     public static String JavaDoc[] removeTrailingEmptyLines(String JavaDoc[] sourceLines) {
318         int lastNonEmpty= findLastNonEmptyLineIndex(sourceLines);
319         String JavaDoc[] result= new String JavaDoc[lastNonEmpty + 1];
320         for (int i= 0; i < result.length; i++) {
321             result[i]= sourceLines[i];
322         }
323         return result;
324     }
325
326     private static int findLastNonEmptyLineIndex(String JavaDoc[] sourceLines) {
327         for (int i= sourceLines.length - 1; i >= 0; i--) {
328             if (! sourceLines[i].trim().equals(""))//$NON-NLS-1$
329
return i;
330         }
331         return -1;
332     }
333     
334     /**
335      * Change the indent of, possible muti-line, code range. The current indent is removed, a new indent added.
336      * The first line of the code will not be changed. (It is considered to have no indent as it might start in
337      * the middle of a line)
338      *
339      * @param project the java project from which to get the formatter
340      * preferences, or <code>null</code> for global preferences
341      * @since 3.1
342      */

343     public static String JavaDoc changeIndent(String JavaDoc code, int codeIndentLevel, IJavaProject project, String JavaDoc newIndent, String JavaDoc lineDelim) {
344         return IndentManipulation.changeIndent(code, codeIndentLevel, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), newIndent, lineDelim);
345     }
346     
347     /**
348      * Change the indent of, possible muti-line, code range. The current indent is removed, a new indent added.
349      * The first line of the code will not be changed. (It is considered to have no indent as it might start in
350      * the middle of a line)
351      * @since 3.1
352      */

353     public static String JavaDoc changeIndent(String JavaDoc code, int codeIndentLevel, int tabWidth, int indentWidth, String JavaDoc newIndent, String JavaDoc lineDelim) {
354         return IndentManipulation.changeIndent(code, codeIndentLevel, tabWidth, indentWidth, newIndent, lineDelim);
355     }
356     
357     public static String JavaDoc trimIndentation(String JavaDoc source, IJavaProject project, boolean considerFirstLine) {
358         return trimIndentation(source, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), considerFirstLine);
359     }
360     
361     public static String JavaDoc trimIndentation(String JavaDoc source, int tabWidth, int indentWidth, boolean considerFirstLine) {
362         try {
363             ILineTracker tracker= new DefaultLineTracker();
364             tracker.set(source);
365             int size= tracker.getNumberOfLines();
366             if (size == 1)
367                 return source;
368             String JavaDoc lines[]= new String JavaDoc[size];
369             for (int i= 0; i < size; i++) {
370                 IRegion region= tracker.getLineInformation(i);
371                 int offset= region.getOffset();
372                 lines[i]= source.substring(offset, offset + region.getLength());
373             }
374             Strings.trimIndentation(lines, tabWidth, indentWidth, considerFirstLine);
375             StringBuffer JavaDoc result= new StringBuffer JavaDoc();
376             int last= size - 1;
377             for (int i= 0; i < size; i++) {
378                 result.append(lines[i]);
379                 if (i < last)
380                     result.append(tracker.getLineDelimiter(i));
381             }
382             return result.toString();
383         } catch (BadLocationException e) {
384             Assert.isTrue(false,"Can not happend"); //$NON-NLS-1$
385
return null;
386         }
387     }
388         
389     
390     /**
391      * Concatenate the given strings into one strings using the passed line delimiter as a
392      * delimiter. No delimiter is added to the last line.
393      */

394     public static String JavaDoc concatenate(String JavaDoc[] lines, String JavaDoc delimiter) {
395         StringBuffer JavaDoc buffer= new StringBuffer JavaDoc();
396         for (int i= 0; i < lines.length; i++) {
397             if (i > 0)
398                 buffer.append(delimiter);
399             buffer.append(lines[i]);
400         }
401         return buffer.toString();
402     }
403     
404     public static boolean equals(String JavaDoc s, char[] c) {
405         if (s.length() != c.length)
406             return false;
407
408         for (int i = c.length; --i >= 0;)
409             if (s.charAt(i) != c[i])
410                 return false;
411         return true;
412     }
413         
414     public static String JavaDoc removeTrailingCharacters(String JavaDoc text, char toRemove) {
415         int size= text.length();
416         int end= size;
417         for (int i= size - 1; i >= 0; i--) {
418             char c= text.charAt(i);
419             if (c == toRemove) {
420                 end= i;
421             } else {
422                 break;
423             }
424         }
425         if (end == size)
426             return text;
427         else if (end == 0)
428             return ""; //$NON-NLS-1$
429
else
430             return text.substring(0, end);
431     }
432     
433     public static String JavaDoc removeMnemonicIndicator(String JavaDoc string) {
434         return LegacyActionTools.removeMnemonics(string);
435     }
436 }
437
Popular Tags