KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > editor > Utilities


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.editor;
21
22 import java.awt.Rectangle JavaDoc;
23 import java.awt.Frame JavaDoc;
24 import java.awt.event.ActionEvent JavaDoc;
25 import java.awt.event.KeyEvent JavaDoc;
26 import java.util.logging.Level JavaDoc;
27 import java.util.logging.Logger JavaDoc;
28 import javax.swing.SwingUtilities JavaDoc;
29 import javax.swing.Action JavaDoc;
30 import javax.swing.KeyStroke JavaDoc;
31 import javax.swing.text.JTextComponent JavaDoc;
32 import javax.swing.text.BadLocationException JavaDoc;
33 import javax.swing.text.EditorKit JavaDoc;
34 import javax.swing.text.Document JavaDoc;
35 import javax.swing.text.TextAction JavaDoc;
36 import javax.swing.text.Caret JavaDoc;
37 import javax.swing.plaf.TextUI JavaDoc;
38 import javax.swing.text.Element JavaDoc;
39 import javax.swing.text.View JavaDoc;
40 import org.netbeans.lib.editor.util.CharSequenceUtilities;
41 import org.netbeans.lib.editor.util.swing.DocumentUtilities;
42 import org.openide.util.NbBundle;
43
44 /**
45 * Various useful editor functions. Some of the methods have
46 * the same names and signatures like in javax.swing.Utilities but
47 * there is also many other useful methods.
48 * All the methods are static so there's no reason to instantiate Utilities.
49 *
50 * All the methods working with the document rely on that it is locked against
51 * modification so they don't acquire document read/write lock by themselves
52 * to guarantee the full thread safety of the execution.
53 * It's the user's task to lock the document appropriately
54 * before using methods described here.
55 *
56 * Most of the methods require org.netbeans.editor.BaseDocument instance
57 * not just the javax.swing.text.Document.
58 * The reason for that is to mark that the methods work on BaseDocument
59 * instances only, not on generic documents. To convert the Document
60 * to BaseDocument the simple conversion (BaseDocument)target.getDocument()
61 * can be done or the method getDocument(target) can be called.
62 * There are also other conversion methods like getEditorUI(), getKit()
63 * or getKitClass().
64 *
65 * @author Miloslav Metelka
66 * @version 0.10
67 */

68
69 public class Utilities {
70
71     private static final String JavaDoc WRONG_POSITION_LOCALE = "wrong_position"; // NOI18N
72

73     /** Switch the case to capital letters. Used in changeCase() */
74     public static final int CASE_UPPER = 0;
75
76     /** Switch the case to small letters. Used in changeCase() */
77     public static final int CASE_LOWER = 1;
78
79     /** Switch the case to reverse. Used in changeCase() */
80     public static final int CASE_SWITCH = 2;
81     
82     /** Fake TextAction for getting the info of the focused component */
83     private static TextAction JavaDoc focusedComponentAction;
84     
85     private Utilities() {
86         // instantiation has no sense
87
}
88
89     /** Get the starting position of the row.
90     * @param c text component to operate on
91     * @param offset position in document where to start searching
92     * @return position of the start of the row or -1 for invalid position
93     */

94     public static int getRowStart(JTextComponent JavaDoc c, int offset)
95     throws BadLocationException JavaDoc {
96         Rectangle JavaDoc r = c.modelToView(offset);
97         if (r == null){
98             return -1;
99         }
100         EditorUI eui = getEditorUI(c);
101         if (eui != null){
102             return c.viewToModel(new java.awt.Point JavaDoc (eui.textLeftMarginWidth, r.y));
103         }
104         return -1;
105     }
106
107     /** Get the starting position of the row.
108     * @param doc document to operate on
109     * @param offset position in document where to start searching
110     * @return position of the start of the row or -1 for invalid position
111     */

112     public static int getRowStart(BaseDocument doc, int offset)
113     throws BadLocationException JavaDoc {
114         return getRowStart(doc, offset, 0);
115     }
116
117     /** Get the starting position of the row while providing relative count
118     * of row how the given position should be shifted. This is the most
119     * efficient way how to move by lines in the document based on some
120     * position. There is no similair getRowEnd() method that would have
121     * shifting parameter.
122     * @param doc document to operate on
123     * @param offset position in document where to start searching
124     * @param lineShift shift the given offset forward/back relatively
125     * by some amount of lines
126     * @return position of the start of the row or -1 for invalid position
127     */

128     public static int getRowStart(BaseDocument doc, int offset, int lineShift)
129     throws BadLocationException JavaDoc {
130         
131         checkOffsetValid(doc, offset);
132
133         if (lineShift != 0) {
134             Element JavaDoc lineRoot = doc.getParagraphElement(0).getParentElement();
135             int line = lineRoot.getElementIndex(offset);
136             line += lineShift;
137             if (line < 0 || line >= lineRoot.getElementCount()) {
138                 return -1; // invalid line shift
139
}
140             return lineRoot.getElement(line).getStartOffset();
141
142         } else { // no shift
143
return doc.getParagraphElement(offset).getStartOffset();
144         }
145     }
146
147     /** Get the first non-white character on the line.
148     * The document.isWhitespace() is used to test whether the particular
149     * character is white space or not.
150     * @param doc document to operate on
151     * @param offset position in document anywhere on the line
152     * @return position of the first non-white char on the line or -1
153     * if there's no non-white character on that line.
154     */

155     public static int getRowFirstNonWhite(BaseDocument doc, int offset)
156     throws BadLocationException JavaDoc {
157         
158         checkOffsetValid(doc, offset);
159
160         Element JavaDoc lineElement = doc.getParagraphElement(offset);
161         return getFirstNonWhiteFwd(doc,
162             lineElement.getStartOffset(),
163             lineElement.getEndOffset() - 1
164         );
165     }
166
167     /** Get the last non-white character on the line.
168     * The document.isWhitespace() is used to test whether the particular
169     * character is white space or not.
170     * @param doc document to operate on
171     * @param offset position in document anywhere on the line
172     * @return position of the last non-white char on the line or -1
173     * if there's no non-white character on that line.
174     */

175     public static int getRowLastNonWhite(BaseDocument doc, int offset)
176     throws BadLocationException JavaDoc {
177         
178         checkOffsetValid(doc, offset);
179
180         Element JavaDoc lineElement = doc.getParagraphElement(offset);
181         return getFirstNonWhiteBwd(doc,
182             lineElement.getEndOffset() - 1,
183             lineElement.getStartOffset()
184         );
185     }
186
187     /** Get indentation on the current line. If this line is white then
188     * return -1.
189     * @param doc document to operate on
190     * @param offset position in document anywhere on the line
191     * @return indentation or -1 if the line is white
192     */

193     public static int getRowIndent(BaseDocument doc, int offset)
194     throws BadLocationException JavaDoc {
195         offset = getRowFirstNonWhite(doc, offset);
196         if (offset == -1) {
197             return -1;
198         }
199         return doc.getVisColFromPos(offset);
200     }
201
202     /** Get indentation on the current line. If this line is white then
203     * go either up or down an return indentation of the first non-white row.
204     * The <tt>getRowFirstNonWhite()</tt> is used to find the indentation
205     * on particular line.
206     * @param doc document to operate on
207     * @param offset position in document anywhere on the line
208     * @param downDir if this flag is set to true then if the row is white
209     * then the indentation of the next first non-white row is returned. If it's
210     * false then the indentation of the previous first non-white row is returned.
211     * @return indentation or -1 if there's no non-white line in the specified direction
212     */

213     public static int getRowIndent(BaseDocument doc, int offset, boolean downDir)
214     throws BadLocationException JavaDoc {
215         int p = getRowFirstNonWhite(doc, offset);
216         if (p == -1) {
217             p = getFirstNonWhiteRow(doc, offset, downDir);
218             if (p == -1) {
219                 return -1; // non-white line not found
220
}
221             p = getRowFirstNonWhite(doc, p);
222             if (p == -1) {
223                 return -1; // non-white line not found
224
}
225         }
226         return doc.getVisColFromPos(p);
227     }
228
229     /** Get the end position of the row right before the new-line character.
230     * @param c text component to operate on
231     * @param offset position in document where to start searching
232     * @param relLine shift offset forward/back by some amount of lines
233     * @return position of the end of the row or -1 for invalid position
234     */

235     public static int getRowEnd(JTextComponent JavaDoc c, int offset)
236     throws BadLocationException JavaDoc {
237         Rectangle JavaDoc r = c.modelToView(offset);
238         if (r == null){
239             return -1;
240         }
241         return c.viewToModel(new java.awt.Point JavaDoc (Integer.MAX_VALUE, r.y));
242     }
243     
244     public static int getRowEnd(BaseDocument doc, int offset)
245     throws BadLocationException JavaDoc {
246         checkOffsetValid(doc, offset);
247
248         return doc.getParagraphElement(offset).getEndOffset() - 1;
249     }
250     
251     private static int findBestSpan(JTextComponent JavaDoc c, int lineBegin, int lineEnd, int x)
252     throws BadLocationException JavaDoc{
253         if (lineBegin == lineEnd){
254             return lineEnd;
255         }
256         int low = lineBegin;
257         int high = lineEnd;
258         while (low <= high) {
259             
260             if (high - low < 3){
261                 int bestSpan = Integer.MAX_VALUE;
262                 int bestPos = -1;
263                 for (int i = low; i<=high; i++){
264                     Rectangle JavaDoc tempRect = c.modelToView(i);
265                     if (Math.abs(x-tempRect.x) < bestSpan){
266                         bestSpan = Math.abs(x-tempRect.x);
267                         bestPos = i;
268                     }
269                 }
270                 return bestPos;
271             }
272             
273             int mid = (low + high) / 2;
274             
275             Rectangle JavaDoc tempRect = c.modelToView(mid);
276             if (tempRect.x > x){
277                 high = mid;
278             } else if (tempRect.x < x) {
279                 low = mid;
280             } else {
281                 return mid;
282             }
283         }
284         return lineBegin;
285     }
286
287     /** Get the position that is one line above and visually at some
288     * x-coordinate value.
289     * @param doc document to operate on
290     * @param offset position in document from which the current line is determined
291     * @param x float x-coordinate value
292     * @return position of the character that is at the one line above at
293     * the required x-coordinate value
294     */

295     public static int getPositionAbove(JTextComponent JavaDoc c, int offset, int x)
296     throws BadLocationException JavaDoc {
297         int rowStart = getRowStart(c, offset);
298         int endInit = c.getUI().getNextVisualPositionFrom(c,
299                               rowStart, null, javax.swing.SwingConstants.WEST, null);
300
301         if (x == BaseKit.MAGIC_POSITION_MAX){
302             return endInit;
303         }
304
305         EditorUI eui = getEditorUI(c);
306         if (eui == null){
307             return offset; //skip
308
}
309         
310         Rectangle JavaDoc r = c.modelToView(endInit);
311         if (r == null){
312             return offset; //skip
313
}
314         
315         if (x == eui.textLeftMarginWidth){
316             return getRowStart(c, endInit);
317         }
318         
319         int end = c.viewToModel(new java.awt.Point JavaDoc(Math.max(eui.textLeftMarginWidth, x + 2*r.width ),r.y));
320         Rectangle JavaDoc tempRect = c.modelToView(end);
321         if (tempRect == null || tempRect.x < x){
322             end = endInit;
323         }
324         
325         int start = c.viewToModel(new java.awt.Point JavaDoc(Math.max(eui.textLeftMarginWidth, x - 2*r.width ),r.y));
326         tempRect = c.modelToView(start);
327         if (tempRect == null && tempRect.x > x){
328             start = getRowStart(c, end);
329         }
330         
331         int best = findBestSpan(c, start, end, x);
332         
333         if (best<c.getDocument().getLength()){
334             // #56056
335
int tmp = best + 1;
336             int nextVisualPosition = c.getUI().getNextVisualPositionFrom(c,
337                     tmp, javax.swing.text.Position.Bias.Backward, javax.swing.SwingConstants.WEST, null);
338             if (nextVisualPosition<best && nextVisualPosition >= 0){
339                 return nextVisualPosition;
340             }
341         }
342         
343         return best;
344     }
345     
346     /** Get the position that is one line above and visually at some
347     * x-coordinate value.
348     * @param c text component to operate on
349     * @param offset position in document from which the current line is determined
350     * @param x float x-coordinate value
351     * @return position of the character that is at the one line above at
352     * the required x-coordinate value
353     */

354     public static int getPositionBelow(JTextComponent JavaDoc c, int offset, int x)
355     throws BadLocationException JavaDoc {
356     int startInit = getRowEnd(c, offset) + 1;
357
358         Rectangle JavaDoc r = c.modelToView(startInit);
359         if (r == null){
360             return offset; // skip
361
}
362         
363         EditorUI eui = getEditorUI(c);
364         if (eui != null && x ==eui.textLeftMarginWidth){
365             return startInit;
366         }
367         
368         int start = c.viewToModel(new java.awt.Point JavaDoc(Math.min(Integer.MAX_VALUE, r.x + x - 2*r.width ),r.y));
369         Rectangle JavaDoc tempRect = c.modelToView(start);
370         if (tempRect!=null && tempRect.x > x){
371             start = startInit;
372         }
373         
374         int end = c.viewToModel(new java.awt.Point JavaDoc(Math.min(Integer.MAX_VALUE, r.x + x + 2*r.width ),r.y));
375         tempRect = c.modelToView(end);
376         if (tempRect!=null && tempRect.x < x){
377             end = getRowEnd(c, start);
378         }
379         
380         int best = findBestSpan(c, start, end, x);
381         
382         if (best>0){
383             // #70254 - make sure $best is not in collapsed fold area. Try
384
// getNextVisualPositionFrom to EAST from the position $best-1.
385
// If the resulted next visual position is not equal to $best,
386
// $best is in the collapsed fold and foldEnd or foldStart
387
// should be returned.
388
int tmp = best - 1;
389             int nextVisualPosition = c.getUI().getNextVisualPositionFrom(c,
390                     tmp, javax.swing.text.Position.Bias.Forward, javax.swing.SwingConstants.EAST, null);
391             if (nextVisualPosition>best && nextVisualPosition <= c.getDocument().getLength()){
392                 // We are in the collapsed fold, now try to find which position
393
// is the best, whether foldEnd or foldStart
394
tempRect = c.modelToView(nextVisualPosition);
395                 if (tempRect == null){
396                     return nextVisualPosition;
397                 }
398                 int rightX = tempRect.x;
399                 int nextVisualPositionLeft = c.getUI().getNextVisualPositionFrom(c,
400                         nextVisualPosition, javax.swing.text.Position.Bias.Backward, javax.swing.SwingConstants.WEST, null);
401                 tempRect = c.modelToView(nextVisualPositionLeft);
402                 if (tempRect == null){
403                     return nextVisualPosition;
404                 }
405                 int leftX = tempRect.x;
406                 
407                 if (Math.abs(leftX - x) > Math.abs(rightX - x)){
408                     return nextVisualPosition;
409                 } else {
410                     return nextVisualPositionLeft;
411                 }
412             }
413         }
414         
415         return best;
416     }
417
418     /** Get start of the current word. If there are no more words till
419     * the begining of the document, this method returns -1.
420     * @param c text component to operate on
421     * @param offset position in document from which the current line is determined
422     */

423     public static int getWordStart(JTextComponent JavaDoc c, int offset)
424     throws BadLocationException JavaDoc {
425         return getWordStart((BaseDocument)c.getDocument(), offset);
426     }
427
428     public static int getWordStart(BaseDocument doc, int offset)
429     throws BadLocationException JavaDoc {
430         return doc.find(new FinderFactory.PreviousWordBwdFinder(doc, false, true),
431                         offset, 0);
432     }
433
434     public static int getWordEnd(JTextComponent JavaDoc c, int offset)
435     throws BadLocationException JavaDoc {
436         return getWordEnd((BaseDocument)c.getDocument(), offset);
437     }
438
439     public static int getWordEnd(BaseDocument doc, int offset)
440     throws BadLocationException JavaDoc {
441         int ret = doc.find(new FinderFactory.NextWordFwdFinder(doc, false, true),
442                         offset, -1);
443         return (ret > 0) ? ret : doc.getLength();
444     }
445
446     public static int getNextWord(JTextComponent JavaDoc c, int offset)
447     throws BadLocationException JavaDoc {
448         int nextWordOffset = getNextWord((BaseDocument)c.getDocument(), offset);
449         int nextVisualPosition = -1;
450         if (nextWordOffset > 0){
451             nextVisualPosition = c.getUI().getNextVisualPositionFrom(c,
452                     nextWordOffset - 1, null, javax.swing.SwingConstants.EAST, null);
453         }
454         return (nextVisualPosition == -1) ? nextWordOffset : nextVisualPosition;
455     }
456
457     public static int getNextWord(BaseDocument doc, int offset)
458     throws BadLocationException JavaDoc {
459         Finder nextWordFinder = (Finder)doc.getProperty(SettingsNames.NEXT_WORD_FINDER);
460         offset = doc.find(nextWordFinder, offset, -1);
461         if (offset < 0) {
462             offset = doc.getLength();
463         }
464         return offset;
465     }
466
467     public static int getPreviousWord(JTextComponent JavaDoc c, int offset)
468     throws BadLocationException JavaDoc {
469         int prevWordOffset = getPreviousWord((BaseDocument)c.getDocument(), offset);
470         int nextVisualPosition = c.getUI().getNextVisualPositionFrom(c,
471                               prevWordOffset, null, javax.swing.SwingConstants.WEST, null);
472         if (nextVisualPosition == 0 && prevWordOffset == 0){
473             return 0;
474         }
475         return (nextVisualPosition + 1 == prevWordOffset) ? prevWordOffset : nextVisualPosition + 1;
476     }
477
478     public static int getPreviousWord(BaseDocument doc, int offset)
479     throws BadLocationException JavaDoc {
480         Finder prevWordFinder = (Finder)doc.getProperty(SettingsNames.PREVIOUS_WORD_FINDER);
481         offset = doc.find(prevWordFinder, offset, 0);
482         if (offset < 0) {
483             offset = 0;
484         }
485         return offset;
486     }
487
488     /** Get first white character in document in forward direction
489     * @param doc document to operate on
490     * @param offset position in document where to start searching
491     * @return position of the first white character or -1
492     */

493     public static int getFirstWhiteFwd(BaseDocument doc, int offset)
494     throws BadLocationException JavaDoc {
495         return getFirstWhiteFwd(doc, offset, -1);
496     }
497
498     /** Get first white character in document in forward direction
499     * @param doc document to operate on
500     * @param offset position in document where to start searching
501     * @param limitPos position in document (greater or equal than offset) where
502     * the search will stop reporting unsuccessful search by returning -1
503     * @return position of the first non-white character or -1
504     */

505     public static int getFirstWhiteFwd(BaseDocument doc, int offset, int limitPos)
506     throws BadLocationException JavaDoc {
507         return doc.find(new FinderFactory.WhiteFwdFinder(doc), offset, limitPos);
508     }
509
510     /** Get first non-white character in document in forward direction
511     * @param doc document to operate on
512     * @param offset position in document where to start searching
513     * @return position of the first non-white character or -1
514     */

515     public static int getFirstNonWhiteFwd(BaseDocument doc, int offset)
516     throws BadLocationException JavaDoc {
517         return getFirstNonWhiteFwd(doc, offset, -1);
518     }
519
520     /** Get first non-white character in document in forward direction
521     * @param doc document to operate on
522     * @param offset position in document where to start searching
523     * @param limitPos position in document (greater or equal than offset) where
524     * the search will stop reporting unsuccessful search by returning -1
525     * @return position of the first non-white character or -1
526     */

527     public static int getFirstNonWhiteFwd(BaseDocument doc, int offset, int limitPos)
528     throws BadLocationException JavaDoc {
529         return doc.find(new FinderFactory.NonWhiteFwdFinder(doc), offset, limitPos);
530     }
531
532     /** Get first white character in document in backward direction.
533     * The character right before the character at position offset will
534     * be searched as first.
535     * @param doc document to operate on
536     * @param offset position in document where to start searching
537     * @return position of the first white character or -1
538     */

539     public static int getFirstWhiteBwd(BaseDocument doc, int offset)
540     throws BadLocationException JavaDoc {
541         return getFirstWhiteBwd(doc, offset, 0);
542     }
543
544     /** Get first white character in document in backward direction.
545     * The character right before the character at position offset will
546     * be searched as first.
547     * @param doc document to operate on
548     * @param offset position in document where to start searching
549     * @param limitPos position in document (lower or equal than offset) where
550     * the search will stop reporting unsuccessful search by returning -1
551     * @return position of the first white character or -1
552     */

553     public static int getFirstWhiteBwd(BaseDocument doc, int offset, int limitPos)
554     throws BadLocationException JavaDoc {
555         return doc.find(new FinderFactory.WhiteBwdFinder(doc), offset, limitPos);
556     }
557
558     /** Get first non-white character in document in backward direction.
559     * The character right before the character at position offset will
560     * be searched as first.
561     * @param doc document to operate on
562     * @param offset position in document where to start searching
563     * @return position of the first non-white character or -1
564     */

565     public static int getFirstNonWhiteBwd(BaseDocument doc, int offset)
566     throws BadLocationException JavaDoc {
567         return getFirstNonWhiteBwd(doc, offset, 0);
568     }
569
570     /** Get first non-white character in document in backward direction.
571     * The character right before the character at position offset will
572     * be searched as first.
573     * @param doc document to operate on
574     * @param offset position in document where to start searching
575     * @param limitPos position in document (lower or equal than offset) where
576     * the search will stop reporting unsuccessful search by returning -1
577     * @return position of the first non-white character or -1
578     */

579     public static int getFirstNonWhiteBwd(BaseDocument doc, int offset, int limitPos)
580     throws BadLocationException JavaDoc {
581         return doc.find(new FinderFactory.NonWhiteBwdFinder(doc), offset, limitPos);
582     }
583
584     /** Return line offset (line number - 1) for some position in the document
585     * @param doc document to operate on
586     * @param offset position in document where to start searching
587     */

588     public static int getLineOffset(BaseDocument doc, int offset)
589     throws BadLocationException JavaDoc {
590         
591         checkOffsetValid(offset, doc.getLength() + 1);
592
593         Element JavaDoc lineRoot = doc.getParagraphElement(0).getParentElement();
594         return lineRoot.getElementIndex(offset);
595     }
596
597     /** Return start offset of the line
598     * @param lineIndex line index starting from 0
599     * @return start position of the line or -1 if lineIndex was invalid
600     */

601     public static int getRowStartFromLineOffset(BaseDocument doc, int lineIndex) {
602         Element JavaDoc lineRoot = doc.getParagraphElement(0).getParentElement();
603         if (lineIndex < 0 || lineIndex >= lineRoot.getElementCount()) {
604             return -1; // invalid line number
605

606         } else {
607             return lineRoot.getElement(lineIndex).getStartOffset();
608         }
609     }
610
611     /** Return visual column (with expanded tabs) on the line.
612     * @param doc document to operate on
613     * @param offset position in document for which the visual column should be found
614     * @return visual column on the line determined by position
615     */

616     public static int getVisualColumn(BaseDocument doc, int offset)
617     throws BadLocationException JavaDoc {
618         
619         int docLen = doc.getLength();
620         if (offset == docLen + 1) { // at ending extra '\n' => make docLen to proceed without BLE
621
offset = docLen;
622         }
623
624         return doc.getVisColFromPos(offset);
625     }
626
627     /** Get the identifier around the given position or null if there's no identifier
628     * @see getIdentifierBlock()
629     */

630     public static String JavaDoc getIdentifier(BaseDocument doc, int offset)
631     throws BadLocationException JavaDoc {
632         int[] blk = getIdentifierBlock(doc, offset);
633         return (blk != null) ? doc.getText(blk[0], blk[1] - blk[0]) : null;
634     }
635
636
637     /** Get the identifier around the given position or null if there's no identifier
638      * around the given position. The identifier is not verified against SyntaxSupport.isIdentifier().
639      * @param c JTextComponent to work on
640      * @param offset position in document - usually the caret.getDot()
641      * @return the block (starting and ending position) enclosing the identifier
642      * or null if no identifier was found
643      */

644     public static int[] getIdentifierBlock(JTextComponent JavaDoc c, int offset)
645     throws BadLocationException JavaDoc {
646         CharSequence JavaDoc id = null;
647         int[] ret = null;
648         Document JavaDoc doc = c.getDocument();
649         int idStart = javax.swing.text.Utilities.getWordStart(c, offset);
650         if (idStart >= 0) {
651             int idEnd = javax.swing.text.Utilities.getWordEnd(c, idStart);
652             if (idEnd >= 0) {
653                 id = DocumentUtilities.getText(doc, idStart, idEnd - idStart);
654                 ret = new int[] { idStart, idEnd };
655                 CharSequence JavaDoc trim = CharSequenceUtilities.trim(id);
656                 if (trim.length() == 0 || (trim.length() == 1 && !Character.isJavaIdentifierPart(trim.charAt(0)))) {
657                     int prevWordStart = javax.swing.text.Utilities.getPreviousWord(c, offset);
658                     if (offset == javax.swing.text.Utilities.getWordEnd(c,prevWordStart )){
659                         ret = new int[] { prevWordStart, offset };
660                     } else {
661                         return null;
662                     }
663                 } else if ((id != null) && (id.length() != 0) && (CharSequenceUtilities.indexOf(id, '.') != -1)){ //NOI18N
664
int index = offset - idStart;
665                     int begin = CharSequenceUtilities.lastIndexOf(id.subSequence(0, index), '.');
666                     begin = (begin == -1) ? 0 : begin + 1; //first index after the dot, if exists
667
int end = CharSequenceUtilities.indexOf(id, '.', index);
668                     end = (end == -1) ? id.length() : end;
669                     ret = new int[] { idStart+begin, idStart+end };
670                 }
671             }
672         }
673         return ret;
674     }
675     
676     
677     
678     /** Get the identifier around the given position or null if there's no identifier
679     * around the given position. The identifier must be
680     * accepted by SyntaxSupport.isIdnetifier() otherwise null is returned.
681     * @param doc document to work on
682     * @param offset position in document - usually the caret.getDot()
683     * @return the block (starting and ending position) enclosing the identifier
684     * or null if no identifier was found
685     */

686     public static int[] getIdentifierBlock(BaseDocument doc, int offset)
687     throws BadLocationException JavaDoc {
688         int[] ret = null;
689         int idStart = getWordStart(doc, offset);
690         if (idStart >= 0) {
691             int idEnd = getWordEnd(doc, idStart);
692             if (idEnd >= 0) {
693                 String JavaDoc id = doc.getText(idStart, idEnd - idStart);
694                 if (doc.getSyntaxSupport().isIdentifier(id)) {
695                     ret = new int[] { idStart, idEnd };
696                 } else { // not identifier by syntax support
697
id = getWord(doc, offset); // try right at offset
698
if (doc.getSyntaxSupport().isIdentifier(id)) {
699                         ret = new int[] { offset, offset + id.length() };
700                     }
701                 }
702             }
703         }
704         return ret;
705     }
706
707     
708     /** Get the word around the given position .
709      * @param c component to work with
710      * @param offset position in document - usually the caret.getDot()
711      * @return the word.
712      */

713     public static String JavaDoc getWord(JTextComponent JavaDoc c, int offset)
714     throws BadLocationException JavaDoc {
715         int[] blk = getIdentifierBlock(c, offset);
716         Document JavaDoc doc = c.getDocument();
717         return (blk != null) ? doc.getText(blk[0], blk[1] - blk[0]) : null;
718     }
719     
720     
721     /** Get the selection if there's any or get the identifier around
722     * the position if there's no selection.
723     * @param c component to work with
724     * @param offset position in document - usually the caret.getDot()
725     * @return the block (starting and ending position) enclosing the identifier
726     * or null if no identifier was found
727     */

728     public static int[] getSelectionOrIdentifierBlock(JTextComponent JavaDoc c, int offset)
729     throws BadLocationException JavaDoc {
730         Document JavaDoc doc = c.getDocument();
731         Caret JavaDoc caret = c.getCaret();
732         int[] ret;
733         if (caret.isSelectionVisible()) {
734             ret = new int[] { c.getSelectionStart(), c.getSelectionEnd() };
735         } else if (doc instanceof BaseDocument){
736             ret = getIdentifierBlock((BaseDocument)doc, caret.getDot());
737         } else {
738             ret = getIdentifierBlock(c, offset);
739         }
740         return ret;
741     }
742
743     /** Get the selection or identifier at the current caret position
744      * @see getSelectionOrIdentifierBlock(JTextComponent, int)
745      */

746     public static int[] getSelectionOrIdentifierBlock(JTextComponent JavaDoc c) {
747         try {
748             return getSelectionOrIdentifierBlock(c, c.getCaret().getDot());
749         } catch (BadLocationException JavaDoc e) {
750             return null;
751         }
752     }
753
754     /** Get the identifier before the given position (ending at given offset)
755     * or null if there's no identifier
756     */

757     public static String JavaDoc getIdentifierBefore(BaseDocument doc, int offset)
758     throws BadLocationException JavaDoc {
759         int wordStart = getWordStart(doc, offset);
760         if (wordStart != -1) {
761             String JavaDoc word = new String JavaDoc(doc.getChars(wordStart,
762                                                   offset - wordStart), 0, offset - wordStart);
763             if (doc.getSyntaxSupport().isIdentifier(word)) {
764                 return word;
765             }
766         }
767         return null;
768     }
769
770     /** Get the selection if there's any or get the identifier around
771     * the position if there's no selection.
772     */

773     public static String JavaDoc getSelectionOrIdentifier(JTextComponent JavaDoc c, int offset)
774     throws BadLocationException JavaDoc {
775         Document JavaDoc doc = c.getDocument();
776         Caret JavaDoc caret = c.getCaret();
777         String JavaDoc ret;
778         if (caret.isSelectionVisible()) {
779             ret = c.getSelectedText();
780         if (ret != null) return ret;
781         }
782     if (doc instanceof BaseDocument){
783         ret = getIdentifier((BaseDocument) doc, caret.getDot());
784         } else {
785         ret = getWord(c, offset);
786     }
787         return ret;
788     }
789
790     /** Get the selection or identifier at the current caret position */
791     public static String JavaDoc getSelectionOrIdentifier(JTextComponent JavaDoc c) {
792         try {
793             return getSelectionOrIdentifier(c, c.getCaret().getDot());
794         } catch (BadLocationException JavaDoc e) {
795             return null;
796         }
797     }
798
799     /** Get the word at given position.
800     */

801     public static String JavaDoc getWord(BaseDocument doc, int offset)
802     throws BadLocationException JavaDoc {
803         int wordEnd = getWordEnd(doc, offset);
804         if (wordEnd != -1) {
805             return new String JavaDoc(doc.getChars(offset, wordEnd - offset), 0,
806                               wordEnd - offset);
807         }
808         return null;
809     }
810
811
812     /** Change the case for specified part of document
813     * @param doc document to operate on
814     * @param offset position in document determines the changed area begining
815     * @param len number of chars to change
816     * @param type either CASE_CAPITAL, CASE_SMALL or CASE_SWITCH
817     */

818     public static boolean changeCase(BaseDocument doc, int offset, int len, int type)
819     throws BadLocationException JavaDoc {
820         char[] orig = doc.getChars(offset, len);
821         char[] changed = (char[])orig.clone();
822         for (int i = 0; i < orig.length; i++) {
823             switch (type) {
824             case CASE_UPPER:
825                 changed[i] = Character.toUpperCase(orig[i]);
826                 break;
827             case CASE_LOWER:
828                 changed[i] = Character.toLowerCase(orig[i]);
829                 break;
830             case CASE_SWITCH:
831                 if (Character.isUpperCase(orig[i])) {
832                     changed[i] = Character.toLowerCase(orig[i]);
833                 } else if (Character.isLowerCase(orig[i])) {
834                     changed[i] = Character.toUpperCase(orig[i]);
835                 }
836                 break;
837             }
838         }
839         // check chars for difference and possibly change document
840
for (int i = 0; i < orig.length; i++) {
841             if (orig[i] != changed[i]) {
842                 doc.atomicLock();
843                 try {
844                     doc.remove(offset, orig.length);
845                     doc.insertString(offset, new String JavaDoc(changed), null);
846                 } finally {
847                     doc.atomicUnlock();
848                 }
849                 return true; // changed
850
}
851         }
852         return false;
853     }
854
855     /** Tests whether the line contains no characters except the ending new-line.
856     * @param doc document to operate on
857     * @param offset position anywhere on the tested line
858     * @return whether the line is empty or not
859     */

860     public static boolean isRowEmpty(BaseDocument doc, int offset)
861     throws BadLocationException JavaDoc {
862         Element JavaDoc lineElement = doc.getParagraphElement(offset);
863         return (lineElement.getStartOffset() + 1 == lineElement.getEndOffset());
864     }
865
866     public static int getFirstNonEmptyRow(BaseDocument doc, int offset, boolean downDir)
867     throws BadLocationException JavaDoc {
868         while (offset != -1 && isRowEmpty(doc, offset)) {
869             offset = getRowStart(doc, offset, downDir ? +1 : -1);
870         }
871         return offset;
872     }
873
874     /** Tests whether the line contains only whitespace characters.
875     * @param doc document to operate on
876     * @param offset position anywhere on the tested line
877     * @return whether the line is empty or not
878     */

879     public static boolean isRowWhite(BaseDocument doc, int offset)
880     throws BadLocationException JavaDoc {
881         Element JavaDoc lineElement = doc.getParagraphElement(offset);
882         offset = doc.find(new FinderFactory.NonWhiteFwdFinder(doc),
883               lineElement.getStartOffset(), lineElement.getEndOffset() - 1);
884         return (offset == -1);
885     }
886
887     public static int getFirstNonWhiteRow(BaseDocument doc, int offset, boolean downDir)
888     throws BadLocationException JavaDoc {
889         if (isRowWhite(doc, offset)) {
890             if (downDir) { // search down for non-white line
891
offset = getFirstNonWhiteFwd(doc, offset);
892             } else { // search up for non-white line
893
offset = getFirstNonWhiteBwd(doc, offset);
894             }
895         }
896         return offset;
897     }
898
899     /** Reformat a block of code.
900     * @param doc document to work with
901     * @param startOffset offset at which the formatting starts
902     * @param endOffset offset at which the formatting ends
903     * @return length of the reformatted code
904     */

905     public static int reformat(BaseDocument doc, int startOffset, int endOffset)
906     throws BadLocationException JavaDoc {
907         return doc.getFormatter().reformat(doc, startOffset, endOffset);
908     }
909
910     /** Reformat the line around the given position. */
911     public static void reformatLine(BaseDocument doc, int pos)
912     throws BadLocationException JavaDoc {
913         int lineStart = getRowStart(doc, pos);
914         int lineEnd = getRowEnd(doc, pos);
915         reformat(doc, lineStart, lineEnd);
916     }
917
918     /** Count of rows between these two positions */
919     public static int getRowCount(BaseDocument doc, int startPos, int endPos)
920     throws BadLocationException JavaDoc {
921         if (startPos > endPos) {
922             return 0;
923         }
924         Element JavaDoc lineRoot = doc.getParagraphElement(0).getParentElement();
925         return lineRoot.getElementIndex(endPos) - lineRoot.getElementIndex(startPos) + 1;
926     }
927
928     /** Get the total count of lines in the document */
929     public static int getRowCount(BaseDocument doc) {
930         return doc.getParagraphElement(0).getParentElement().getElementCount();
931     }
932
933     /** @deprecated
934      * @see Formatter.insertTabString()
935      */

936     public static String JavaDoc getTabInsertString(BaseDocument doc, int offset)
937     throws BadLocationException JavaDoc {
938         int col = getVisualColumn(doc, offset);
939         Formatter f = doc.getFormatter();
940         boolean expandTabs = f.expandTabs();
941         if (expandTabs) {
942             int spacesPerTab = f.getSpacesPerTab();
943             int len = (col + spacesPerTab) / spacesPerTab * spacesPerTab - col;
944             return new String JavaDoc(Analyzer.getSpacesBuffer(len), 0, len);
945         } else { // insert pure tab
946
return "\t"; // NOI18N
947
}
948     }
949
950     /** Get the visual column corresponding to the position after pressing
951      * the TAB key.
952      * @param doc document to work with
953      * @param offset position at which the TAB was pressed
954      */

955     public static int getNextTabColumn(BaseDocument doc, int offset)
956     throws BadLocationException JavaDoc {
957         int col = getVisualColumn(doc, offset);
958         int tabSize = doc.getFormatter().getSpacesPerTab();
959         return (col + tabSize) / tabSize * tabSize;
960     }
961
962     public static void setStatusText(JTextComponent JavaDoc c, String JavaDoc text) {
963         StatusBar sb = getEditorUI(c).getStatusBar();
964         if (sb != null) {
965             sb.setText(StatusBar.CELL_MAIN, text);
966         }
967     }
968
969     public static void setStatusText(JTextComponent JavaDoc c, String JavaDoc text,
970                                      Coloring extraColoring) {
971         StatusBar sb = getEditorUI(c).getStatusBar();
972         if (sb != null) {
973             sb.setText(StatusBar.CELL_MAIN, text, extraColoring);
974         }
975     }
976
977     public static void setStatusBoldText(JTextComponent JavaDoc c, String JavaDoc text) {
978         StatusBar sb = getEditorUI(c).getStatusBar();
979         if (sb != null) {
980             sb.setBoldText(StatusBar.CELL_MAIN, text);
981         }
982     }
983
984     public static String JavaDoc getStatusText(JTextComponent JavaDoc c) {
985         StatusBar sb = getEditorUI(c).getStatusBar();
986         return (sb != null) ? sb.getText(StatusBar.CELL_MAIN) : null;
987     }
988
989     public static void clearStatusText(JTextComponent JavaDoc c) {
990         setStatusText(c, ""); // NOI18N
991
}
992
993     public static void insertMark(BaseDocument doc, Mark mark, int offset)
994     throws BadLocationException JavaDoc, InvalidMarkException {
995         mark.insert(doc, offset);
996     }
997
998     public static void moveMark(BaseDocument doc, Mark mark, int newOffset)
999     throws BadLocationException JavaDoc, InvalidMarkException {
1000        mark.move(doc, newOffset);
1001    }
1002
1003    public static void returnFocus() {
1004         JTextComponent JavaDoc c = getLastActiveComponent();
1005         if (c != null) {
1006             requestFocus(c);
1007         }
1008    }
1009
1010    public static void requestFocus(JTextComponent JavaDoc c) {
1011        if (c != null) {
1012            if (!ImplementationProvider.getDefault().activateComponent(c)) {
1013                Frame JavaDoc f = EditorUI.getParentFrame(c);
1014                if (f != null) {
1015                    f.requestFocus();
1016                }
1017                c.requestFocus();
1018            }
1019        }
1020    }
1021
1022    public static void runInEventDispatchThread(Runnable JavaDoc r) {
1023        if (SwingUtilities.isEventDispatchThread()) {
1024            r.run();
1025        } else {
1026            SwingUtilities.invokeLater(r);
1027        }
1028    }
1029
1030    public static String JavaDoc debugPosition(BaseDocument doc, int offset) {
1031        String JavaDoc ret;
1032
1033        if (offset >= 0) {
1034            try {
1035                int line = getLineOffset(doc, offset) + 1;
1036                int col = getVisualColumn(doc, offset) + 1;
1037                ret = String.valueOf(line) + ":" + String.valueOf(col); // NOI18N
1038
} catch (BadLocationException JavaDoc e) {
1039                ret = NbBundle.getBundle(BaseKit.class).getString( WRONG_POSITION_LOCALE )
1040                      + ' ' + offset + " > " + doc.getLength(); // NOI18N
1041
}
1042        } else {
1043            ret = String.valueOf(offset);
1044        }
1045
1046        return ret;
1047    }
1048    
1049    public static String JavaDoc offsetToLineColumnString(BaseDocument doc, int offset) {
1050        return String.valueOf(offset) + "[" + debugPosition(doc, offset) + "]"; // NOI18N
1051
}
1052
1053    /** Display the identity of the document together with the title property
1054     * and stream-description property.
1055     */

1056    public static String JavaDoc debugDocument(Document JavaDoc doc) {
1057        return "<" + System.identityHashCode(doc) // NOI18N
1058
+ ", title='" + doc.getProperty(Document.TitleProperty)
1059            + "', stream='" + doc.getProperty(Document.StreamDescriptionProperty)
1060            + ", " + doc.toString() + ">"; // NOI18N
1061
}
1062
1063    public static void performAction(Action JavaDoc a, ActionEvent JavaDoc evt, JTextComponent JavaDoc target) {
1064        if (a instanceof BaseAction) {
1065            ((BaseAction)a).actionPerformed(evt, target);
1066        } else {
1067            a.actionPerformed(evt);
1068        }
1069    }
1070
1071    /** Returns last activated component. If the component was closed,
1072     * then previous component is returned */

1073    public static JTextComponent JavaDoc getLastActiveComponent() {
1074        return Registry.getMostActiveComponent();
1075    }
1076    
1077    /**
1078     * Fetches the text component that currently has focus. It delegates to
1079     * TextAction.getFocusedComponent().
1080     * @return the component
1081     */

1082    public static JTextComponent JavaDoc getFocusedComponent() {
1083        /** Fake action for getting the focused component */
1084        class FocusedComponentAction extends TextAction JavaDoc {
1085            
1086            FocusedComponentAction() {
1087                super("focused-component"); // NOI18N
1088
}
1089            
1090            /** adding this method because of protected final getFocusedComponent */
1091            JTextComponent JavaDoc getFocusedComponent2() {
1092                return getFocusedComponent();
1093            }
1094            
1095            public void actionPerformed(ActionEvent JavaDoc evt){}
1096        };
1097        
1098        if (focusedComponentAction == null) {
1099            focusedComponentAction = new FocusedComponentAction();
1100        }
1101        
1102        return ((FocusedComponentAction)focusedComponentAction).getFocusedComponent2();
1103    }
1104
1105    /** Helper method to obtain instance of EditorUI (extended UI)
1106     * from the existing JTextComponent.
1107     * It doesn't require any document locking.
1108     * @param target JTextComponent for which the extended UI should be obtained
1109     * @return extended ui instance or null if the component.getUI()
1110     * does not return BaseTextUI instance.
1111     */

1112    public static EditorUI getEditorUI(JTextComponent JavaDoc target) {
1113        TextUI JavaDoc ui = target.getUI();
1114        return (ui instanceof BaseTextUI)
1115            ? ((BaseTextUI)ui).getEditorUI()
1116            : null;
1117    }
1118
1119    /** Helper method to obtain instance of editor kit from existing JTextComponent.
1120    * If the kit of the component is not an instance
1121    * of the <tt>org.netbeans.editor.BaseKit</tt> the method returns null.
1122    * The method doesn't require any document locking.
1123    * @param target JTextComponent for which the editor kit should be obtained
1124    * @return BaseKit instance or null
1125    */

1126    public static BaseKit getKit(JTextComponent JavaDoc target) {
1127        if (target == null) return null; // #19574
1128
EditorKit JavaDoc ekit = target.getUI().getEditorKit(target);
1129        return (ekit instanceof BaseKit) ? (BaseKit)ekit : null;
1130    }
1131
1132    /**
1133     * Gets the class of an editor kit installed in <code>JTextComponent</code>.
1134     * The method doesn't require any document locking.
1135     *
1136     * <div class="nonnormative">
1137     * <p>WARNING: The implementation class of an editor kit is most likely
1138     * not what you want. Please see {@link BaseKit#getKit(Class)} for more
1139     * details.
1140     *
1141     * <p>Unfortunatelly, there are still places in editor libraries where
1142     * an editor kit class is required.
1143     * One of them is the editor settings infrastructure built around the
1144     * <code>Settings</code> class. So, if you really need it go ahead and use it,
1145     * there is nothing wrong with the method itself.
1146     * </div>
1147     *
1148     * @param target The <code>JTextComponent</code> to get the kit class for.
1149     * Can be <code>null</code>.
1150     * @return The implementation class of the editor kit or <code>null</code>
1151     * if the <code>target</code> is <code>null</code>.
1152     */

1153    public static Class JavaDoc getKitClass(JTextComponent JavaDoc target) {
1154        EditorKit JavaDoc kit = (target != null) ? target.getUI().getEditorKit(target) : null;
1155        return (kit != null) ? kit.getClass() : null;
1156    }
1157
1158    /** Helper method to obtain instance of BaseDocument from JTextComponent.
1159    * If the document of the component is not an instance
1160    * of the <tt>org.netbeans.editor.BaseDocument</tt> the method returns null.
1161    * The method doesn't require any document locking.
1162    * @param target JTextComponent for which the document should be obtained
1163    * @return BaseDocument instance or null
1164    */

1165    public static BaseDocument getDocument(JTextComponent JavaDoc target) {
1166        Document JavaDoc doc = target.getDocument();
1167        return (doc instanceof BaseDocument) ? (BaseDocument)doc : null;
1168    }
1169
1170    /** Get the syntax-support class that belongs to the document of the given
1171    * component. Besides using directly this method, the <tt>SyntaxSupport</tt>
1172    * can be obtained by calling <tt>doc.getSyntaxSupport()</tt>.
1173    * The method can return null in case the document is not
1174    * an instance of the BaseDocument.
1175    * The method doesn't require any document locking.
1176    * @param target JTextComponent for which the syntax-support should be obtained
1177    * @return SyntaxSupport instance or null
1178    */

1179    public static SyntaxSupport getSyntaxSupport(JTextComponent JavaDoc target) {
1180        Document JavaDoc doc = target.getDocument();
1181        return (doc instanceof BaseDocument) ? ((BaseDocument)doc).getSyntaxSupport() : null;
1182    }
1183
1184    /**
1185     * Get first view in the hierarchy that is an instance of the given class.
1186     * It allows to skip various wrapper-views around the doc-view that holds
1187     * the child views for the lines.
1188     *
1189     * @param component component from which the root view is fetched.
1190     * @param rootViewClass class of the view to return.
1191     * @return view being instance of the requested class or null if there
1192     * is not one.
1193     */

1194    public static View JavaDoc getRootView(JTextComponent JavaDoc component, Class JavaDoc rootViewClass) {
1195        View JavaDoc view = null;
1196        TextUI JavaDoc textUI = component.getUI();
1197        if (textUI != null) {
1198            view = textUI.getRootView(component);
1199            while (view != null && !rootViewClass.isInstance(view)
1200                && view.getViewCount() == 1 // must be wrapper view
1201
) {
1202                view = view.getView(0); // get the only child
1203
}
1204        }
1205        
1206        return view;
1207    }
1208    
1209    /**
1210     * Get the view that covers the whole area of the document
1211     * and holds a child view for each line in the document
1212     * (or for a bunch of lines in case there is a code folding present).
1213     */

1214    public static View JavaDoc getDocumentView(JTextComponent JavaDoc component) {
1215        return getRootView(component, DrawEngineDocView.class);
1216    }
1217
1218    /**
1219     * Creates nice textual description of sequence of KeyStrokes. Usable for
1220     * displaying MultiKeyBindings. The keyStrokes are delimited by space.
1221     * @param Array of KeyStrokes representing the actual sequence.
1222     * @return String describing the KeyStroke sequence.
1223     */

1224    public static String JavaDoc keySequenceToString( KeyStroke JavaDoc[] seq ) {
1225        StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1226        for( int i=0; i<seq.length; i++ ) {
1227            if( i>0 ) sb.append( ' ' ); // NOI18N
1228
sb.append( keyStrokeToString( seq[i] ) );
1229        }
1230        return sb.toString();
1231    }
1232
1233    /**
1234     * Creates nice textual representation of KeyStroke.
1235     * Modifiers and an actual key label are concated by plus signs
1236     * @param the KeyStroke to get description of
1237     * @return String describing the KeyStroke
1238     */

1239    public static String JavaDoc keyStrokeToString( KeyStroke JavaDoc stroke ) {
1240        String JavaDoc modifText = KeyEvent.getKeyModifiersText( stroke.getModifiers() );
1241        String JavaDoc keyText = (stroke.getKeyCode() == KeyEvent.VK_UNDEFINED) ?
1242            String.valueOf(stroke.getKeyChar()) : getKeyText(stroke.getKeyCode());
1243        if( modifText.length() > 0 ) return modifText + '+' + keyText;
1244        else return keyText;
1245    }
1246    
1247    /** @return slight modification of what KeyEvent.getKeyText() returns.
1248     * The numpad Left, Right, Down, Up get extra result.
1249     */

1250    private static String JavaDoc getKeyText(int keyCode) {
1251        String JavaDoc ret = KeyEvent.getKeyText(keyCode);
1252        if (ret != null) {
1253            switch (keyCode) {
1254                case KeyEvent.VK_KP_DOWN:
1255                    ret = prefixNumpad(ret, KeyEvent.VK_DOWN);
1256                    break;
1257                case KeyEvent.VK_KP_LEFT:
1258                    ret = prefixNumpad(ret, KeyEvent.VK_LEFT);
1259                    break;
1260                case KeyEvent.VK_KP_RIGHT:
1261                    ret = prefixNumpad(ret, KeyEvent.VK_RIGHT);
1262                    break;
1263                case KeyEvent.VK_KP_UP:
1264                    ret = prefixNumpad(ret, KeyEvent.VK_UP);
1265                    break;
1266            }
1267        }
1268        return ret;
1269    }
1270    
1271    private static String JavaDoc prefixNumpad(String JavaDoc key, int testKeyCode) {
1272        if (key.equals(KeyEvent.getKeyText(testKeyCode))) {
1273            key = NbBundle.getBundle(BaseKit.class).getString("key-prefix-numpad") + key;
1274        }
1275        return key;
1276    }
1277
1278    private static void checkOffsetValid(Document JavaDoc doc, int offset) throws BadLocationException JavaDoc {
1279        checkOffsetValid(offset, doc.getLength());
1280    }
1281
1282    private static void checkOffsetValid(int offset, int limitOffset) throws BadLocationException JavaDoc {
1283        if (offset < 0 || offset > limitOffset) {
1284            throw new BadLocationException JavaDoc("Invalid offset=" + offset // NOI18N
1285
+ " not within <0, " + limitOffset + ">", // NOI18N
1286
offset);
1287        }
1288    }
1289
1290    /**
1291     * Writes a <code>Throwable</code> to a log file.
1292     *
1293     * <p class="nonnormative">The method is internally using
1294     * <code>org.netbeans.editor</code> logger and <code>Level.INFO</code>.
1295     *
1296     * @param t The exception that will be logged.
1297     * @deprecated Use java.util.logging.Logger instead with the proper name,
1298     * log level and message.
1299     */

1300    public static void annotateLoggable(Throwable JavaDoc t) {
1301        Logger.getLogger("org.netbeans.editor").log(Level.INFO, null, t); //NOI18N
1302
}
1303    
1304}
1305
Popular Tags