KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snow > texteditor > DocumentUtils


1 package snow.texteditor;
2
3 import snow.Basics;
4 import javax.swing.text.*;
5 import javax.swing.*;
6 import java.awt.*;
7 import java.util.*;
8 import java.io.*;
9
10 public final class DocumentUtils
11 {
12   private DocumentUtils()
13   {
14   }
15
16   /** indent the lines between the given document positions (NOT LINE NUMBERS !)
17   */

18   public static void indentLines(Document doc, int fromPos, int toPos)
19   {
20      int lineStart = getLineNumber( doc, fromPos);
21      int lineEnd = getLineNumber( doc, toPos );
22
23      for(int line =lineStart; line<=lineEnd; line++)
24      {
25         try
26         {
27           Element li = doc.getDefaultRootElement().getElement(line);
28           doc.insertString(li.getStartOffset(), " ", li.getAttributes());
29         } catch(Exception JavaDoc e) { e.printStackTrace(); }
30      }
31   }
32
33
34
35   /** Indents the lines between the given document positions (positions, NOT LINE NUMBERS !)
36   */

37   public static void unindentLines(Document doc, int fromPos, int toPos)
38   {
39      int lineStart = getLineNumber( doc, fromPos);
40      int lineEnd = getLineNumber( doc, toPos );
41
42      for(int line =lineStart; line<=lineEnd; line++)
43      {
44         try
45         {
46            Element li = doc.getDefaultRootElement().getElement(line);
47            char ci = doc.getText(li.getStartOffset(), 1).charAt(0);
48            if(Character.isWhitespace(ci) && ci!='\n')
49            {
50               doc.remove(li.getStartOffset(), 1);
51            }
52         } catch(Exception JavaDoc e) { e.printStackTrace(); }
53      }
54   }
55
56
57   /** comment out the lines between the given document positions (NOT LINE NUMBERS !)
58   * comment out means adding "//" at the beginning of the line.
59   * the uncommentout is the reverse operation
60   */

61   public static void commentOutLines(Document doc, int fromPos, int toPos)
62   {
63      int lineStart = getLineNumber( doc, fromPos);
64      int lineEnd = getLineNumber( doc, toPos );
65
66      for(int line =lineStart; line<=lineEnd; line++)
67      {
68         try
69         {
70           Element li = doc.getDefaultRootElement().getElement(line);
71           doc.insertString(li.getStartOffset(), "//", li.getAttributes());
72         } catch(Exception JavaDoc e) { e.printStackTrace(); }
73      }
74   }
75
76   /** uncomment out the lines between the given document positions (NOT LINE NUMBERS !)
77   * reverse operation of commentOut. This only removes // at the beginning
78   */

79   public static void unCommentOutLines(Document doc, int fromPos, int toPos)
80   {
81      int lineStart = getLineNumber( doc, fromPos);
82      int lineEnd = getLineNumber( doc, toPos );
83
84      for(int line =lineStart; line<=lineEnd; line++)
85      {
86         try
87         {
88            Element li = doc.getDefaultRootElement().getElement(line);
89            if(li.getEndOffset()-li.getStartOffset()>1)
90            {
91              if(doc.getText(li.getStartOffset(), 2).equals("//"))
92              {
93                 doc.remove(li.getStartOffset(), 2);
94             }
95           }
96         } catch(Exception JavaDoc e) { e.printStackTrace(); }
97      }
98   }
99
100
101
102
103   /** normally search an {, with close }
104   */

105   public static int getPreviousOpeningPosition(SimpleDocument doc, char toSearch, char close, int from, int skipCount)
106   {
107        int found = 0;
108     l1:for(int pos=from; pos>=0; pos--)
109        {
110          char c = doc.getCharAt(pos);
111          if(c==close) found--;
112          if(c==toSearch) found++;
113          if(found>skipCount) return pos;
114        }
115        return -1;
116   }
117
118
119
120
121   /** take a java single word yyy, NOT xxx.yyy.zzz like the standard editor kit
122       pos must be in the word or at the beginning.
123       give pos-1 if you want the word before the caret.
124   */

125   public static String JavaDoc getWordAt(SimpleDocument doc, int pos)
126   {
127      try
128      {
129        // search for the bounds of a word
130
int start = pos;
131        int end = pos;
132     l1:for(start=pos; start>=0; start--)
133        {
134          char c = doc.getCharAt(start);
135          if(!Character.isJavaIdentifierPart(c))
136          {
137            if(Character.isJavaIdentifierStart(c)) // ? sense ? can be part if not start ?
138
{
139              // accept it
140
break l1;
141            }
142            else
143            {
144              // refuse it
145
start++;
146              break l1;
147            }
148          }
149        }
150
151     l2:for(end=pos; end<doc.getLength(); end++)
152        {
153           char c = doc.getCharAt(end);
154           if(!Character.isJavaIdentifierPart(c)) break l2;
155        }
156
157        //System.out.println("text from "+start+" to "+end);
158
if(start<0) start=0;
159        if(start>=end) return null; // not found
160

161        return doc.getText(start, end-start);
162      }
163      catch(Exception JavaDoc e)
164      {
165        e.printStackTrace();
166      }
167      return null;
168   }
169
170
171   /** used to find the id on which the mouse is in the editor.
172   */

173   public static int getWordEndPosition(SimpleDocument doc, int posInWord)
174   {
175      try
176      {
177        // search for the bounds of a word
178
int end = posInWord;
179
180     l2:for(; end<doc.getLength(); end++)
181        {
182           char c = doc.getCharAt(end);
183           if(!Character.isJavaIdentifierPart(c)) break l2;
184        }
185
186        //System.out.println("text from "+start+" to "+end);
187
return end;
188      }
189      catch(Exception JavaDoc e)
190      {
191        e.printStackTrace();
192      }
193      return -1;
194   }
195
196
197   public static void main(String JavaDoc[] a)
198   {
199     String JavaDoc str = " hello ";
200     for(int i=0; i<str.length(); i++)
201     {
202       System.out.println(Character.isJavaIdentifierPart(str.charAt(i)));
203     }
204   }
205
206   /** @return the line number corresponding to the document position.
207   * the first line has index 0.
208   */

209   public static int getLineNumber(Document doc, int pos)
210   {
211      // a document is modelled as a list of lines (Element)=> index = line number
212
Element map = doc.getDefaultRootElement();
213      int line = map.getElementIndex(pos);
214      return line;
215   }
216
217   /* not used alone... always together with the line. so we minimize mismatch with offset !
218   * @return the column, first is 0
219   * use getLineColumnNumbers() to directly receive line and column numbers !
220   *
221   public static int getColumnNumber_(Document doc, int pos)
222   {
223      Element map = doc.getDefaultRootElement();
224      int line = map.getElementIndex(pos);
225      Element lineElt = map.getElement(line);
226      return pos-lineElt.getStartOffset();
227   }*/

228
229   /** @return the {line,column}, first is 0
230   */

231   public static int[] getLineColumnNumbers(Document doc, int pos)
232   {
233      Element map = doc.getDefaultRootElement();
234      int line = map.getElementIndex(pos);
235      Element lineElt = map.getElement(line);
236      return new int[]{ line, pos-lineElt.getStartOffset()};
237   }
238
239   public static int getLineStartOffsetForPos(StyledDocument doc, int pos)
240   {
241      // a document is modelled as a list of lines (Element)=> index = line number
242
Element line = doc.getParagraphElement(pos);
243       return line.getStartOffset();
244   }
245
246   public static void deleteLineAtPos(StyledDocument doc, int pos) throws Exception JavaDoc
247   {
248       Element line = doc.getParagraphElement(pos);
249       doc.remove(line.getStartOffset(), line.getEndOffset()-line.getStartOffset());
250   }
251
252   /** @return the text at the line containing the given position. With eventual carriage return and line feeds...
253   */

254   public static String JavaDoc getTextOfLineAtPosition(StyledDocument doc, int pos)
255   {
256      // a document is modelled as a list of lines (Element)=> index = line number
257
Element line = doc.getParagraphElement(pos);
258      try
259      {
260        return doc.getText(line.getStartOffset(), line.getEndOffset()-line.getStartOffset());
261      } catch(Exception JavaDoc e) { return null; }
262   }
263
264   /** @return the text at the line containing the given position
265   */

266   public static String JavaDoc getTextOfLineAtPosition_onlyUpToPos(StyledDocument doc, int pos)
267   {
268      // a document is modelled as a list of lines (Element)=> index = line number
269
Element line = doc.getParagraphElement(pos);
270      try
271      {
272        return doc.getText(line.getStartOffset(), pos-line.getStartOffset());
273      } catch(Exception JavaDoc e) { return null; }
274   }
275
276   /** @return the text at the line containing the given position
277   */

278   public static String JavaDoc getTextOfLine(Document doc, int line)
279   {
280      // a document is modelled as a list of lines (Element)=> index = line number
281
Element map = doc.getDefaultRootElement();
282      Element lineElt = map.getElement(line);
283      try
284      {
285        return doc.getText(lineElt.getStartOffset(), lineElt.getEndOffset()-lineElt.getStartOffset());
286      }
287      catch(Exception JavaDoc e) { return null; }
288   }
289
290   /** -1 if not found open = '{', close = '}'
291    TODO: ignore comments and string quotes ...
292   */

293   public static int getPositionOfCorrespondingOpeningBrace(char open, char close, SimpleDocument doc, int pos)
294   {
295     int level = 0;
296     try
297     {
298       for(int i=pos-1; i>=0; i--)
299       {
300         char ci = doc.getCharAt(i);
301         if(ci==close) level++;
302         if(ci==open)
303         {
304           if(level<=0)
305           {
306             return i;
307           }
308           level--;
309         }
310       }
311     }
312     catch(Exception JavaDoc e) { e.printStackTrace(); }
313
314     return -1;
315   }
316
317   /** -1 if not found open = '{', close = '}'
318    TODO: ignore comments and string quotes ...
319   */

320   public static int getPositionOfCorrespondingClosingBrace(char open, char close, SimpleDocument doc, int pos)
321   {
322     int level = 0;
323     try
324     {
325       //int len = doc.getLength()
326
for(int i=pos+1; i<doc.getLength(); i++)
327       {
328         char ci = doc.getCharAt(i);
329         if(ci==open) level++;
330         if(ci==close)
331         {
332           if(level<=0)
333           {
334             return i;
335           }
336           level--;
337         }
338       }
339     }
340     catch(Exception JavaDoc e) { e.printStackTrace(); }
341
342     return -1;
343   }
344
345
346   public static String JavaDoc getSpacesAtBeginning(String JavaDoc text)
347   {
348     StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
349     for(int i=0; i<text.length(); i++)
350     {
351        char ci = text.charAt(i);
352        if(Character.isWhitespace(ci)
353            && ci!='\r' && ci!='\n')
354        {
355          sb.append(text.charAt(i));
356        }
357        else
358        {
359          break;
360        }
361     }
362     return sb.toString();
363   }
364
365
366   public static void scrollPosToMiddle(int pos, JTextPane textPane, JScrollPane editorScrollPane, int h)
367   {
368        try
369        {
370          Rectangle r = textPane.modelToView(pos);
371          //r.translate(0,-this.getHeight()/4);
372
//textPane.scrollRectToVisible( r );
373
//this.scroll
374
//int h2 = (int)editorScrollPane.getViewport().getExtentSize().getHeight()/2;
375
//System.out.println(""+h2);
376
editorScrollPane.getViewport().setViewPosition(
377               new Point(0, Math.max(r.y - h, 0)) );
378          //textPane.requestFocus(); // to make the selection visible
379

380        } catch(Exception JavaDoc e) { Basics.ignore(e); }
381   }
382
383
384   /** in fact, 1/4 below upper limit is nicer...
385       scrolls the start of the line to the middle of the screen
386   */

387   public static void scrollToMiddle(JTextComponent tp, int pos)
388   {
389      // look if a parent exists, this is only the case IF the text pane has been added in a scrollpane
390
if(tp.getParent()==null) return;
391      if(!(tp.getParent() instanceof JViewport))
392      {
393         new Throwable JavaDoc("parent of textpane is not a viewport !").printStackTrace();
394      }
395
396      JViewport vp = (JViewport) tp.getParent();
397
398      try
399      {
400        Rectangle pt = tp.modelToView(pos);
401        int h = (int)(pt.getY() - vp.getHeight()/4);
402        if(h<0) h = 0;
403        vp.setViewPosition( new Point(0, h) );
404      }
405      catch(Exception JavaDoc e)
406      {
407        e.printStackTrace();
408      }
409   }
410
411   public static int[] getVisibleDocPosBounds(JTextPane textPane, JScrollPane editorScrollPane)
412   {
413      int[] pos = new int[2];
414      try
415      {
416          Point pt = editorScrollPane.getViewport().getViewPosition();
417          pos[0] = textPane.viewToModel(pt);
418          Dimension dim = editorScrollPane.getViewport().getExtentSize();
419
420          Point pt2 = new Point((int)(pt.getX()+dim.getWidth()),(int)(pt.getY()+dim.getHeight()));
421          pos[1] = textPane.viewToModel(pt2);
422          //System.out.println(""+h2);
423
}
424      catch(Exception JavaDoc e) { e.printStackTrace(); }
425      return pos;
426   }
427
428   /** @param line zero based.
429   * @param column zero based
430   */

431   public static int getDocPositionFor(Document doc, int line, int column)
432   {
433      if(line<0) return -1;
434      Element map = doc.getDefaultRootElement();
435      Element lineElt = map.getElement(line);
436      try
437      {
438        int pos = lineElt.getStartOffset() + (column>0?column:0);
439        if(pos<0) return 0; // [April2007]: security...
440
if(pos>doc.getLength()) return doc.getLength();
441        return pos;
442      }
443      catch(Exception JavaDoc e) { throw new RuntimeException JavaDoc(e); }
444   }
445
446 }
Popular Tags