KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > gjt > sp > util > StandardUtilities


1 /*
2  * StandardUtilities.java - Various miscallaneous utility functions
3  * :tabSize=8:indentSize=8:noTabs=false:
4  * :folding=explicit:collapseFolds=1:
5  *
6  * Copyright (C) 1999, 2006 Matthieu Casanova, Slava Pestov
7  * Portions copyright (C) 2000 Richard S. Hall
8  * Portions copyright (C) 2001 Dirk Moebius
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  */

24
25 package org.gjt.sp.util;
26
27
28 //{{{ Imports
29
import javax.swing.text.Segment JavaDoc;
30 import java.util.Comparator JavaDoc;
31 import java.util.Stack JavaDoc;
32 //}}}
33

34 /**
35  * Several tools that depends on JDK only.
36  *
37  * @author Matthieu Casanova
38  * @version $Id: StandardUtilities.java 6808 2006-08-26 23:22:57Z vanza $
39  * @since 4.3pre5
40  */

41 public class StandardUtilities
42 {
43
44     //{{{ Text methods
45

46     //{{{ getLeadingWhiteSpace() method
47
/**
48      * Returns the number of leading white space characters in the
49      * specified string.
50      * @param str The string
51      */

52     public static int getLeadingWhiteSpace(String JavaDoc str)
53     {
54         int whitespace = 0;
55 loop: for(;whitespace < str.length();)
56         {
57             switch(str.charAt(whitespace))
58             {
59             case ' ':
60             case '\t':
61                 whitespace++;
62                 break;
63             default:
64                 break loop;
65             }
66         }
67         return whitespace;
68     } //}}}
69

70     //{{{ getTrailingWhiteSpace() method
71
/**
72      * Returns the number of trailing whitespace characters in the
73      * specified string.
74      * @param str The string
75      */

76     public static int getTrailingWhiteSpace(String JavaDoc str)
77     {
78         int whitespace = 0;
79 loop: for(int i = str.length() - 1; i >= 0; i--)
80         {
81             switch(str.charAt(i))
82             {
83                 case ' ':
84                 case '\t':
85                     whitespace++;
86                     break;
87                 default:
88                     break loop;
89             }
90         }
91         return whitespace;
92     } //}}}
93

94     //{{{ getLeadingWhiteSpaceWidth() method
95
/**
96      * Returns the width of the leading white space in the specified
97      * string.
98      * @param str The string
99      * @param tabSize The tab size
100      */

101     public static int getLeadingWhiteSpaceWidth(String JavaDoc str, int tabSize)
102     {
103         int whitespace = 0;
104 loop: for(int i = 0; i < str.length(); i++)
105         {
106             switch(str.charAt(i))
107             {
108                 case ' ':
109                     whitespace++;
110                     break;
111                 case '\t':
112                     whitespace += tabSize -
113                         whitespace % tabSize;
114                     break;
115                 default:
116                     break loop;
117             }
118         }
119         return whitespace;
120     } //}}}
121

122     //{{{ createWhiteSpace() method
123
/**
124      * Creates a string of white space with the specified length.<p>
125      *
126      * To get a whitespace string tuned to the current buffer's
127      * settings, call this method as follows:
128      *
129      * <pre>myWhitespace = MiscUtilities.createWhiteSpace(myLength,
130      * (buffer.getBooleanProperty("noTabs") ? 0
131      * : buffer.getTabSize()));</pre>
132      *
133      * @param len The length
134      * @param tabSize The tab size, or 0 if tabs are not to be used
135      */

136     public static String JavaDoc createWhiteSpace(int len, int tabSize)
137     {
138         return createWhiteSpace(len,tabSize,0);
139     } //}}}
140

141     //{{{ createWhiteSpace() method
142
/**
143      * Creates a string of white space with the specified length.<p>
144      *
145      * To get a whitespace string tuned to the current buffer's
146      * settings, call this method as follows:
147      *
148      * <pre>myWhitespace = MiscUtilities.createWhiteSpace(myLength,
149      * (buffer.getBooleanProperty("noTabs") ? 0
150      * : buffer.getTabSize()));</pre>
151      *
152      * @param len The length
153      * @param tabSize The tab size, or 0 if tabs are not to be used
154      * @param start The start offset, for tab alignment
155      */

156     public static String JavaDoc createWhiteSpace(int len, int tabSize, int start)
157     {
158         StringBuilder JavaDoc buf = new StringBuilder JavaDoc();
159         if(tabSize == 0)
160         {
161             while(len-- > 0)
162                 buf.append(' ');
163         }
164         else if(len == 1)
165             buf.append(' ');
166         else
167         {
168             int count = (len + start % tabSize) / tabSize;
169             if(count != 0)
170                 len += start;
171             while(count-- > 0)
172                 buf.append('\t');
173             count = len % tabSize;
174             while(count-- > 0)
175                 buf.append(' ');
176         }
177         return buf.toString();
178     } //}}}
179

180     //{{{ getVirtualWidth() method
181
/**
182      * Returns the virtual column number (taking tabs into account) of the
183      * specified offset in the segment.
184      *
185      * @param seg The segment
186      * @param tabSize The tab size
187      */

188     public static int getVirtualWidth(Segment JavaDoc seg, int tabSize)
189     {
190         int virtualPosition = 0;
191
192         for (int i = 0; i < seg.count; i++)
193         {
194             char ch = seg.array[seg.offset + i];
195
196             if (ch == '\t')
197             {
198                 virtualPosition += tabSize
199                     - virtualPosition % tabSize;
200             }
201             else
202             {
203                 ++virtualPosition;
204             }
205         }
206
207         return virtualPosition;
208     } //}}}
209

210     //{{{ getOffsetOfVirtualColumn() method
211
/**
212      * Returns the array offset of a virtual column number (taking tabs
213      * into account) in the segment.
214      *
215      * @param seg The segment
216      * @param tabSize The tab size
217      * @param column The virtual column number
218      * @param totalVirtualWidth If this array is non-null, the total
219      * virtual width will be stored in its first location if this method
220      * returns -1.
221      *
222      * @return -1 if the column is out of bounds
223      */

224     public static int getOffsetOfVirtualColumn(Segment JavaDoc seg, int tabSize,
225                         int column, int[] totalVirtualWidth)
226     {
227         int virtualPosition = 0;
228
229         for (int i = 0; i < seg.count; i++)
230         {
231             char ch = seg.array[seg.offset + i];
232
233             if (ch == '\t')
234             {
235                 int tabWidth = tabSize
236                     - virtualPosition % tabSize;
237                 if(virtualPosition >= column)
238                     return i;
239                 else
240                     virtualPosition += tabWidth;
241             }
242             else
243             {
244                 if(virtualPosition >= column)
245                     return i;
246                 else
247                     ++virtualPosition;
248             }
249         }
250
251         if(totalVirtualWidth != null)
252             totalVirtualWidth[0] = virtualPosition;
253         return -1;
254     } //}}}
255

256     //{{{ compareStrings() method
257
/**
258      * Compares two strings.<p>
259      *
260      * Unlike <function>String.compareTo()</function>,
261      * this method correctly recognizes and handles embedded numbers.
262      * For example, it places "My file 2" before "My file 10".<p>
263      *
264      * @param str1 The first string
265      * @param str2 The second string
266      * @param ignoreCase If true, case will be ignored
267      * @return negative If str1 &lt; str2, 0 if both are the same,
268      * positive if str1 &gt; str2
269      * @since jEdit 4.3pre5
270      */

271     public static int compareStrings(String JavaDoc str1, String JavaDoc str2, boolean ignoreCase)
272     {
273         char[] char1 = str1.toCharArray();
274         char[] char2 = str2.toCharArray();
275
276         int len = Math.min(char1.length,char2.length);
277
278         for(int i = 0, j = 0; i < len && j < len; i++, j++)
279         {
280             char ch1 = char1[i];
281             char ch2 = char2[j];
282             if(Character.isDigit(ch1) && Character.isDigit(ch2)
283                 && ch1 != '0' && ch2 != '0')
284             {
285                 int _i = i + 1;
286                 int _j = j + 1;
287
288                 for(; _i < char1.length; _i++)
289                 {
290                     if(!Character.isDigit(char1[_i]))
291                     {
292                         //_i--;
293
break;
294                     }
295                 }
296
297                 for(; _j < char2.length; _j++)
298                 {
299                     if(!Character.isDigit(char2[_j]))
300                     {
301                         //_j--;
302
break;
303                     }
304                 }
305
306                 int len1 = _i - i;
307                 int len2 = _j - j;
308                 if(len1 > len2)
309                     return 1;
310                 else if(len1 < len2)
311                     return -1;
312                 else
313                 {
314                     for(int k = 0; k < len1; k++)
315                     {
316                         ch1 = char1[i + k];
317                         ch2 = char2[j + k];
318                         if(ch1 != ch2)
319                             return ch1 - ch2;
320                     }
321                 }
322
323                 i = _i - 1;
324                 j = _j - 1;
325             }
326             else
327             {
328                 if(ignoreCase)
329                 {
330                     ch1 = Character.toLowerCase(ch1);
331                     ch2 = Character.toLowerCase(ch2);
332                 }
333
334                 if(ch1 != ch2)
335                     return ch1 - ch2;
336             }
337         }
338
339         return char1.length - char2.length;
340     } //}}}
341

342     //{{{ StringCompare class
343
/**
344      * Compares strings.
345      */

346     public static class StringCompare implements Comparator JavaDoc
347         {
348         public int compare(Object JavaDoc obj1, Object JavaDoc obj2)
349         {
350             return compareStrings(obj1.toString(),
351                 obj2.toString(),false);
352         }
353     } //}}}
354

355     //{{{ objectsEqual() method
356
/**
357      * Returns if two strings are equal. This correctly handles null pointers,
358      * as opposed to calling <code>o1.equals(o2)</code>.
359      * @since jEdit 4.3pre6
360      */

361     public static boolean objectsEqual(Object JavaDoc o1, Object JavaDoc o2)
362     {
363         if(o1 == null)
364         {
365             if(o2 == null)
366                 return true;
367             else
368                 return false;
369         }
370         else if(o2 == null)
371             return false;
372         else
373             return o1.equals(o2);
374     } //}}}
375

376     //{{{ globToRE() method
377
/**
378      * Converts a Unix-style glob to a regular expression.<p>
379      *
380      * ? becomes ., * becomes .*, {aa,bb} becomes (aa|bb).
381      * @param glob The glob pattern
382      * @since jEdit 4.3pre7
383      */

384     public static String JavaDoc globToRE(String JavaDoc glob)
385     {
386         final Object JavaDoc NEG = new Object JavaDoc();
387         final Object JavaDoc GROUP = new Object JavaDoc();
388         Stack JavaDoc state = new Stack JavaDoc();
389
390         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
391         boolean backslash = false;
392
393         for(int i = 0; i < glob.length(); i++)
394         {
395             char c = glob.charAt(i);
396             if(backslash)
397             {
398                 buf.append('\\');
399                 buf.append(c);
400                 backslash = false;
401                 continue;
402             }
403
404             switch(c)
405             {
406             case '\\':
407                 backslash = true;
408                 break;
409             case '?':
410                 buf.append('.');
411                 break;
412             case '.':
413             case '+':
414             case '(':
415             case ')':
416                 buf.append('\\');
417                 buf.append(c);
418                 break;
419             case '*':
420                 buf.append(".*");
421                 break;
422             case '|':
423                 if(backslash)
424                     buf.append("\\|");
425                 else
426                     buf.append('|');
427                 break;
428             case '{':
429                 buf.append('(');
430                 if(i + 1 != glob.length() && glob.charAt(i + 1) == '!')
431                 {
432                     buf.append('?');
433                     state.push(NEG);
434                 }
435                 else
436                     state.push(GROUP);
437                 break;
438             case ',':
439                 if(!state.isEmpty() && state.peek() == GROUP)
440                     buf.append('|');
441                 else
442                     buf.append(',');
443                 break;
444             case '}':
445                 if(!state.isEmpty())
446                 {
447                     buf.append(")");
448                     if(state.pop() == NEG)
449                         buf.append(".*");
450                 }
451                 else
452                     buf.append('}');
453                 break;
454             default:
455                 buf.append(c);
456             }
457         }
458
459         return buf.toString();
460     } //}}}
461

462     //}}}
463
private StandardUtilities(){}
464 }
465
Popular Tags