KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > languages > javascript > JavaScript


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.modules.languages.javascript;
21
22 import java.util.HashSet JavaDoc;
23 import java.util.ListIterator JavaDoc;
24 import java.util.ListIterator JavaDoc;
25 import java.util.Set JavaDoc;
26 import org.netbeans.api.languages.ASTItem;
27 import org.netbeans.api.languages.CharInput;
28 import org.netbeans.api.languages.DatabaseManager;
29 import org.netbeans.api.languages.LibrarySupport;
30 import org.netbeans.api.languages.ASTNode;
31 import org.netbeans.api.languages.ASTPath;
32 import org.netbeans.api.languages.SyntaxContext;
33 import org.netbeans.api.languages.support.CompletionSupport;
34 import org.netbeans.api.lexer.Token;
35 import org.netbeans.api.lexer.TokenHierarchy;
36 import org.netbeans.api.lexer.TokenSequence;
37 import org.netbeans.modules.editor.NbEditorDocument;
38 import org.netbeans.modules.editor.NbEditorUtilities;
39 import org.netbeans.api.languages.Context;
40 import org.netbeans.api.languages.LibrarySupport;
41 import org.netbeans.api.languages.SyntaxContext;
42 import org.netbeans.api.languages.ASTNode;
43 import org.netbeans.api.languages.ASTToken;
44 import org.netbeans.modules.languages.javascript.Semantic.Declaration;
45 import org.openide.DialogDisplayer;
46 import org.openide.ErrorManager;
47 import org.openide.ErrorManager;
48 import org.openide.NotifyDescriptor;
49 import org.openide.cookies.EditCookie;
50 import org.openide.cookies.EditorCookie;
51 import org.openide.cookies.SaveCookie;
52 import org.openide.loaders.DataObject;
53 import org.openide.text.Line;
54 import org.openide.text.NbDocument;
55 import org.openide.windows.IOProvider;
56 import org.openide.windows.InputOutput;
57 import java.io.IOException JavaDoc;
58 import java.io.Reader JavaDoc;
59 import java.io.Writer JavaDoc;
60 import java.lang.reflect.InvocationTargetException JavaDoc;
61 import java.lang.reflect.Method JavaDoc;
62 import java.util.ArrayList JavaDoc;
63 import java.util.Collection JavaDoc;
64 import java.util.Iterator JavaDoc;
65 import java.util.List JavaDoc;
66 import javax.swing.text.BadLocationException JavaDoc;
67 import javax.swing.text.Caret JavaDoc;
68 import javax.swing.text.Document JavaDoc;
69 import javax.swing.text.JTextComponent JavaDoc;
70 import javax.swing.text.StyledDocument JavaDoc;
71 import javax.swing.text.StyledDocument JavaDoc;
72 import org.openide.cookies.LineCookie;
73
74
75 /**
76  *
77  * @author Jan Jancura, Dan Prusa
78  */

79 public class JavaScript {
80
81     private static final String JavaDoc DOC = "org/netbeans/modules/languages/javascript/Documentation.xml";
82     private static final String JavaDoc MIME_TYPE = "text/javascript";
83     
84     private static Set JavaDoc regExp = new HashSet JavaDoc ();
85     static {
86         regExp.add (new Integer JavaDoc (','));
87         regExp.add (new Integer JavaDoc (')'));
88         regExp.add (new Integer JavaDoc (';'));
89     }
90     
91     public static Object JavaDoc[] parseRegularExpression (CharInput input) {
92         if (input.read () != '/')
93             throw new InternalError JavaDoc ();
94         int start = input.getIndex ();
95         while (!input.eof () &&
96                 input.next () != '/'
97         ) {
98             if (input.next () == '\r' ||
99                 input.next () == '\n'
100             ) {
101                 input.setIndex (start);
102                 return new Object JavaDoc[] {
103                     ASTToken.create (MIME_TYPE, "js_operator", "", 0),
104                     null
105                 };
106             }
107             if (input.next () == '\\')
108                 input.read ();
109             input.read ();
110         }
111         while (input.next () == '/') input.read ();
112         while (!input.eof ()) {
113             int ch = input.next ();
114             if (ch != 'g' && ch != 'i' && ch != 'm')
115                 break;
116             input.read ();
117         }
118         int end = input.getIndex ();
119         while (
120             !input.eof () && (
121                 input.next () == ' ' ||
122                 input.next () == '\t'
123             )
124         )
125             input.read ();
126         if (
127             !input.eof () &&
128             input.next () == '.'
129         ) {
130             int h = input.getIndex ();
131             input.read ();
132             if (input.next () >= '0' &&
133                 input.next () <= '9'
134             ) {
135                 input.setIndex (start);
136                 return new Object JavaDoc[] {
137                     ASTToken.create (MIME_TYPE, "js_operator", "", 0),
138                     null
139                 };
140             } else {
141                 input.setIndex (end);
142                 return new Object JavaDoc[] {
143                     ASTToken.create (MIME_TYPE, "js_regularExpression", "", 0),
144                     null
145                 };
146             }
147         }
148         if (
149             !input.eof () && regExp.contains (new Integer JavaDoc (input.next ()))
150         ) {
151             input.setIndex (end);
152             return new Object JavaDoc[] {
153                 ASTToken.create (MIME_TYPE, "js_regularExpression", "", 0),
154                 null
155             };
156         }
157         input.setIndex (start);
158         return new Object JavaDoc[] {
159             ASTToken.create (MIME_TYPE, "js_operator", "", 0),
160             null
161         };
162     }
163
164     public static Runnable JavaDoc hyperlink (SyntaxContext context) {
165         ASTPath path = context.getASTPath ();
166         ASTToken t = (ASTToken) path.getLeaf ();
167         ASTNode n = path.size () > 1 ?
168             (ASTNode) path.get (path.size () - 2) :
169             null;
170         String JavaDoc name = t.getIdentifier ();
171         DatabaseManager databaseManager = DatabaseManager.getDefault ();
172         List JavaDoc<Line.Part> list = databaseManager.get (path, name, false);
173         if (list.isEmpty ())
174             list = databaseManager.get (DatabaseManager.FOLDER, name);
175         if (list.isEmpty ()) return null;
176         final Line.Part l = list.get (0);
177         if (l == null) return null;
178         DataObject dataObject = (DataObject) l.getLine ().getLookup ().
179             lookup (DataObject.class);
180         EditorCookie ec = (EditorCookie) dataObject.getCookie (EditCookie.class);
181         StyledDocument JavaDoc document = ec.getDocument ();
182         int offset = NbDocument.findLineOffset (
183             document,
184             l.getLine ().getLineNumber ()
185         ) + l.getColumn ();
186         if (offset == t.getOffset ()) return null;
187         return new Runnable JavaDoc () {
188             public void run () {
189                 l.getLine ().show (Line.SHOW_GOTO, l.getColumn ());
190             }
191         };
192     }
193     
194     public static String JavaDoc functionName (SyntaxContext context) {
195         ASTPath path = context.getASTPath ();
196         ASTNode n = (ASTNode) path.getLeaf ();
197         String JavaDoc name = null;
198         ASTNode nameNode = n.getNode ("FunctionName");
199         if (nameNode != null)
200             name = nameNode.getAsText ();
201         String JavaDoc parameters = "";
202         ASTNode parametersNode = n.getNode ("FormalParameterList");
203         if (parametersNode != null)
204             parameters = parametersNode.getAsText ();
205         if (name != null) return name + " (" + parameters + ")";
206         
207         ListIterator JavaDoc<ASTItem> it = path.listIterator (path.size () - 1);
208         while (it.hasPrevious ()) {
209             ASTItem item = it.previous ();
210             if (item instanceof ASTToken) break;
211             ASTNode p = (ASTNode) item;
212             if (p.getNT ().equals ("AssignmentExpressionInitial") &&
213                 p.getNode ("AssignmentOperator") != null
214             ) {
215                 return ((ASTNode) p.getChildren ().get (0)).getAsText () +
216                     " (" + getAsText (n.getNode ("FormalParameterList")) + ")";
217             }
218             if (p.getNT ().equals ("PropertyNameAndValue")) {
219                 return p.getNode ("PropertyName").getAsText () +
220                     " (" + getAsText (n.getNode ("FormalParameterList")) + ")";
221             }
222         }
223         return "?";
224     }
225
226     public static String JavaDoc objectName (SyntaxContext context) {
227         ASTPath path = context.getASTPath ();
228         ASTNode n = (ASTNode) path.getLeaf ();
229         ListIterator JavaDoc<ASTItem> it = path.listIterator (path.size ());
230         while (it.hasPrevious ()) {
231             ASTItem item = it.previous ();
232             if (item instanceof ASTToken) break;
233             ASTNode p = (ASTNode) item;
234             if (p.getNT ().equals ("AssignmentExpressionInitial") &&
235                 p.getNode ("AssignmentOperator") != null
236             ) {
237                 return ((ASTNode) p.getChildren ().get (0)).getAsText ();
238             }
239             if (p.getNT ().equals ("PropertyNameAndValue")) {
240                 return p.getNode ("PropertyName").getAsText ();
241             }
242         }
243         return "?";
244     }
245     
246     
247     // code completion .........................................................
248

249     public static List JavaDoc completionItems (Context context) {
250         List JavaDoc result = new ArrayList JavaDoc ();
251         if (context instanceof SyntaxContext) {
252             ASTPath path = ((SyntaxContext) context).getASTPath ();
253             DatabaseManager databaseManager = DatabaseManager.getDefault ();
254             Collection JavaDoc c = databaseManager.getIds (path, true);
255             result.addAll (c);
256             c = databaseManager.getIds (DatabaseManager.FOLDER);
257             result.addAll (c);
258             return result;
259         }
260         
261         TokenSequence ts = context.getTokenSequence ();
262         Token token = ts.token ();
263         String JavaDoc tokenText = token.text ().toString ();
264         String JavaDoc libraryContext = null;
265         if (tokenText.equals (".")) {
266             token = previousToken (ts);
267             if (token.id ().name ().endsWith ("identifier"))
268                 libraryContext = token.text ().toString ();
269         } else
270         if (token.id ().name ().endsWith ("identifier") ) {
271             token = previousToken (ts);
272             if (token.text ().toString ().equals (".")) {
273                 token = previousToken (ts);
274                 if (token.id ().name ().endsWith ("identifier"))
275                     libraryContext = token.text ().toString ();
276             }
277         }
278         
279         if (libraryContext != null) {
280             result.addAll (getFromLibrary (libraryContext, 1, "black"));
281             result.addAll (getFromLibrary ("member", 2, "black"));
282         } else
283             result.addAll (getFromLibrary ("keyword", 2, "blue"));
284         result.addAll (getFromLibrary ("root",2, "black"));
285         return result;
286     }
287     
288     private static Token previousToken (TokenSequence ts) {
289         do {
290             if (!ts.movePrevious ()) return ts.token ();
291         } while (ts.token ().id ().name ().endsWith ("whitespace"));
292         return ts.token ();
293     }
294     
295     private static List JavaDoc getFromLibrary (
296         String JavaDoc context,
297         int priority,
298         String JavaDoc color
299     ) {
300         List JavaDoc l = getLibrary ().getItems (context);
301         List JavaDoc result = new ArrayList JavaDoc ();
302         if (l == null) return result;
303         Iterator JavaDoc it = l.iterator ();
304         while (it.hasNext ()) {
305             String JavaDoc item = (String JavaDoc) it.next ();
306             String JavaDoc description = getLibrary ().getProperty
307                 (context, item, "description");
308             if (description == null)
309                 result.add (CompletionSupport.createCompletionItem (
310                     item,
311                     "<html><b><font color=" + color + ">" + item +
312                         "</font></b></html>",
313                     null,
314                     priority
315                 ));
316             else
317                 result.add (CompletionSupport.createCompletionItem (
318                     item,
319                     "<html><b><font color=" + color + ">" + item +
320                         ": </font></b><font color=black> " +
321                         description + "</font></html>",
322                     null,
323                     priority
324                 ));
325         }
326         return result;
327     }
328
329     private static List JavaDoc completionDescriptions;
330
331     public static List JavaDoc completionDescriptions (Context context) {
332         return completionItems (context);
333 // if (completionDescriptions == null) {
334
// List tags = completionItems (context);
335
// tags = completionItems;
336
// completionDescriptions = new ArrayList (tags.size ());
337
// Iterator it = tags.iterator ();
338
// while (it.hasNext ()) {
339
// String tag = (String) it.next ();
340
// String description = getLibrary ().getProperty
341
// ("keyword", tag, "description");
342
// if (description != null) {
343
// completionDescriptions.add (
344
// "<html><b><font color=blue>" + tag +
345
// ": </font></b><font color=black> " +
346
// description + "</font></html>"
347
// );
348
// } else {
349
// description = getLibrary ().getProperty
350
// ("root", tag, "description");
351
// if (description == null)
352
// completionDescriptions.add (
353
// "<html><b><font color=black>" + tag +
354
// "</font></b></html>"
355
// );
356
// else
357
// completionDescriptions.add (
358
// "<html><b><font color=black>" + tag +
359
// ": </font></b><font color=black> " +
360
// description + "</font></html>"
361
// );
362
// }
363
// }
364
// }
365
// if (!(context instanceof SyntaxContext)) return completionDescriptions;
366
// ASTPath path = ((SyntaxContext) context).getASTPath ();
367
// ArrayList l = new ArrayList ();
368
// DatabaseManager databaseManager = DatabaseManager.getDefault ();
369
// Collection c = databaseManager.getIds ((ASTNode) path.get (path.size () - 2), true);
370
// l.addAll (c);
371
// c = databaseManager.getIds (DatabaseManager.FOLDER);
372
// l.addAll (c);
373
// l.addAll (completionDescriptions);
374
// return l;
375
}
376     
377     
378     // actions .................................................................
379

380     public static void performDeleteCurrentMethod (ASTNode node, JTextComponent JavaDoc comp) {
381         NbEditorDocument doc = (NbEditorDocument)comp.getDocument();
382         int position = comp.getCaretPosition();
383         ASTPath path = node.findPath(position);
384         ASTNode methodNode = null;
385         for (Iterator JavaDoc iter = path.listIterator(); iter.hasNext(); ) {
386             Object JavaDoc obj = iter.next();
387             if (!(obj instanceof ASTNode))
388                 break;
389             ASTNode n = (ASTNode) obj;
390             if ("FunctionDeclaration".equals(n.getNT())) { // NOI18N
391
methodNode = n;
392             } // if
393
} // for
394
if (methodNode != null) {
395             try {
396                 doc.remove(methodNode.getOffset(), methodNode.getLength());
397             } catch (BadLocationException JavaDoc e) {
398                 ErrorManager.getDefault().notify(e);
399             }
400         }
401     }
402      
403     public static boolean enabledDeleteCurrentMethod (ASTNode node, JTextComponent JavaDoc comp) {
404         NbEditorDocument doc = (NbEditorDocument)comp.getDocument();
405         int position = comp.getCaretPosition();
406         ASTPath path = node.findPath(position);
407         if (path == null) return false;
408         for (Iterator JavaDoc iter = path.listIterator(); iter.hasNext(); ) {
409             Object JavaDoc obj = iter.next();
410             if (!(obj instanceof ASTNode))
411                 return false;
412             ASTNode n = (ASTNode) obj;
413             if ("FunctionDeclaration".equals(n.getNT())) { // NOI18N
414
return true;
415             } // if
416
} // for
417
return false;
418     }
419     
420     public static void performRun (ASTNode node, JTextComponent JavaDoc comp) {
421         ClassLoader JavaDoc cl = JavaScript.class.getClassLoader ();
422         try {
423 // ScriptEngineManager manager = new ScriptEngineManager ();
424
// ScriptEngine engine = manager.getEngineByMimeType ("text/javascript");
425
Class JavaDoc managerClass = cl.loadClass ("javax.script.ScriptEngineManager");
426             Object JavaDoc manager = managerClass.newInstance();
427             Method JavaDoc getEngineByMimeType = managerClass.getMethod ("getEngineByMimeType", new Class JavaDoc[] {String JavaDoc.class});
428             Object JavaDoc engine = getEngineByMimeType.invoke (manager, new Object JavaDoc[] {"text/javascript"});
429             
430             Document doc = comp.getDocument ();
431             DataObject dob = NbEditorUtilities.getDataObject (doc);
432             String JavaDoc name = dob.getPrimaryFile ().getNameExt ();
433             SaveCookie saveCookie = (SaveCookie) dob.getLookup ().lookup (SaveCookie.class);
434             if (saveCookie != null)
435                 try {
436                     saveCookie.save ();
437                 } catch (IOException JavaDoc ex) {
438                     ErrorManager.getDefault ().notify (ex);
439                 }
440             
441 // ScriptContext context = engine.getContext ();
442
Class JavaDoc engineClass = cl.loadClass ("javax.script.ScriptEngine");
443             Method JavaDoc getContext = engineClass.getMethod ("getContext", new Class JavaDoc[] {});
444             Object JavaDoc context = getContext.invoke (engine, new Object JavaDoc[] {});
445             
446             InputOutput io = IOProvider.getDefault ().getIO ("Run " + name, false);
447             
448 // context.setWriter (io.getOut ());
449
// context.setErrorWriter (io.getErr ());
450
// context.setReader (io.getIn ());
451
Class JavaDoc contextClass = cl.loadClass("javax.script.ScriptContext");
452             Method JavaDoc setWriter = contextClass.getMethod ("setWriter", new Class JavaDoc[] {Writer JavaDoc.class});
453             Method JavaDoc setErrorWriter = contextClass.getMethod ("setErrorWriter", new Class JavaDoc[] {Writer JavaDoc.class});
454             Method JavaDoc setReader = contextClass.getMethod ("setReader", new Class JavaDoc[] {Reader JavaDoc.class});
455             setWriter.invoke (context, new Object JavaDoc[] {io.getOut ()});
456             setErrorWriter.invoke (context, new Object JavaDoc[] {io.getErr ()});
457             setReader.invoke (context, new Object JavaDoc[] {io.getIn ()});
458             
459             io.getOut().reset ();
460             io.getErr ().reset ();
461             io.select ();
462             
463 // Object o = engine.eval (doc.getText (0, doc.getLength ()));
464
Method JavaDoc eval = engineClass.getMethod ("eval", new Class JavaDoc[] {String JavaDoc.class});
465             Object JavaDoc o = eval.invoke (engine, new Object JavaDoc[] {doc.getText (0, doc.getLength ())});
466             
467             if (o != null)
468                 DialogDisplayer.getDefault ().notify (new NotifyDescriptor.Message ("Result: " + o));
469             
470         } catch (InvocationTargetException JavaDoc ex) {
471             try {
472                 Class JavaDoc scriptExceptionClass = cl.loadClass("javax.script.ScriptException");
473                 if (ex.getCause () != null &&
474                     scriptExceptionClass.isAssignableFrom (ex.getCause ().getClass ())
475                 )
476                     DialogDisplayer.getDefault ().notify (new NotifyDescriptor.Message (ex.getCause ().getMessage ()));
477                 else
478                     ErrorManager.getDefault ().notify (ex);
479             } catch (Exception JavaDoc ex2) {
480                 ErrorManager.getDefault ().notify (ex2);
481             }
482         } catch (Exception JavaDoc ex) {
483             ErrorManager.getDefault ().notify (ex);
484         }
485 // ScriptEngineManager manager = new ScriptEngineManager ();
486
// ScriptEngine engine = manager.getEngineByMimeType ("text/javascript");
487
// Document doc = comp.getDocument ();
488
// DataObject dob = NbEditorUtilities.getDataObject (doc);
489
// String name = dob.getPrimaryFile ().getNameExt ();
490
// SaveCookie saveCookie = (SaveCookie) dob.getLookup ().lookup (SaveCookie.class);
491
// if (saveCookie != null)
492
// try {
493
// saveCookie.save ();
494
// } catch (IOException ex) {
495
// ErrorManager.getDefault ().notify (ex);
496
// }
497
// try {
498
// ScriptContext context = engine.getContext ();
499
// InputOutput io = IOProvider.getDefault ().getIO ("Run " + name, false);
500
// context.setWriter (io.getOut ());
501
// context.setErrorWriter (io.getErr ());
502
// context.setReader (io.getIn ());
503
// io.select ();
504
// Object o = engine.eval (doc.getText (0, doc.getLength ()));
505
// if (o != null)
506
// DialogDisplayer.getDefault ().notify (new NotifyDescriptor.Message ("Result: " + o));
507
// } catch (BadLocationException ex) {
508
// ErrorManager.getDefault ().notify (ex);
509
// } catch (ScriptException ex) {
510
// DialogDisplayer.getDefault ().notify (new NotifyDescriptor.Message (ex.getMessage ()));
511
// }
512
}
513
514     public static boolean enabledRun (ASTNode node, JTextComponent JavaDoc comp) {
515         try {
516             ClassLoader JavaDoc cl = JavaScript.class.getClassLoader ();
517             Class JavaDoc managerClass = cl.loadClass ("javax.script.ScriptEngineManager");
518
519             return managerClass != null;
520         } catch (ClassNotFoundException JavaDoc ex) {
521             return false;
522         }
523     }
524     
525     public static void performGoToDeclaration (ASTNode node, JTextComponent JavaDoc comp) {
526         NbEditorDocument doc = (NbEditorDocument)comp.getDocument();
527         int position = comp.getCaretPosition();
528         ASTPath path = node.findPath(position);
529         ASTItem item = path.getLeaf();
530         if (!(item instanceof ASTToken)) {
531             return;
532         }
533         DatabaseManager manager = DatabaseManager.getDefault();
534         Semantic.Info info = Semantic.getInfo(doc);
535         Semantic.Declaration decl = info.getItem(item);
536         if (info == null || decl == null) {
537             return;
538         }
539         int offset = decl.getASTItem().getOffset();
540         DataObject dobj = NbEditorUtilities.getDataObject (doc);
541         LineCookie lc = (LineCookie)dobj.getCookie(LineCookie.class);
542         Line.Set lineSet = lc.getLineSet();
543         Line line = lineSet.getCurrent(NbDocument.findLineNumber(doc, offset));
544         int column = NbDocument.findLineColumn (doc, offset);
545         line.show (Line.SHOW_GOTO, column);
546     }
547      
548     public static boolean enabledGoToDeclaration (ASTNode node, JTextComponent JavaDoc comp) {
549         NbEditorDocument doc = (NbEditorDocument)comp.getDocument();
550         int position = comp.getCaretPosition();
551         ASTPath path = node.findPath(position);
552         ASTItem item = path.getLeaf();
553         if (!(item instanceof ASTToken)) {
554             return false;
555         }
556         DatabaseManager manager = DatabaseManager.getDefault();
557         Semantic.Info info = Semantic.getInfo(doc);
558         return info != null && info.getItem(item) != null;
559     }
560     
561     public static boolean isFunctionParameter (Context context) {
562         return isVariable(context, Declaration.PARAMETER);
563     }
564     
565     public static boolean isLocalVariable(Context context) {
566         return isVariable(context, Declaration.LOCAL_VARIABLE);
567     }
568     
569     // helper methods ..........................................................
570

571     private static boolean isVariable(Context context, int kind) {
572         if (!(context instanceof SyntaxContext)) {
573             return false;
574         }
575         SyntaxContext scontext = (SyntaxContext)context;
576         ASTPath path = scontext.getASTPath ();
577         Object JavaDoc obj = path.getLeaf ();
578         if (!(obj instanceof ASTToken)) {
579             return false;
580         }
581         ASTToken leaf = (ASTToken)obj;
582         Semantic.Info info = Semantic.getInfo(scontext.getDocument());
583         if (info == null) return false;
584         Declaration decl = info.getItem(leaf);
585         return decl != null && decl.getKind() == kind;
586     }
587     
588     private static LibrarySupport library;
589     
590     private static LibrarySupport getLibrary () {
591         if (library == null)
592             library = LibrarySupport.create (DOC);
593         return library;
594     }
595
596     private static TokenSequence getTokenSequence (Document doc, Caret JavaDoc caret) {
597         int ln = NbDocument.findLineNumber ((StyledDocument JavaDoc) doc, caret.getDot ()) - 1;
598         int start = NbDocument.findLineOffset ((StyledDocument JavaDoc) doc, ln);
599         TokenHierarchy th = TokenHierarchy.get (doc);
600         TokenSequence ts = th.tokenSequence ();
601         ts.move (start);
602         return ts;
603     }
604     
605     private static void indent (Document doc, Caret JavaDoc caret, int i) {
606         StringBuilder JavaDoc sb = new StringBuilder JavaDoc ();
607         while (i > 0) {
608             sb.append (' ');i--;
609         }
610         try {
611             doc.insertString (caret.getDot (), sb.toString (), null);
612         } catch (BadLocationException JavaDoc ex) {
613             ErrorManager.getDefault ().notify (ex);
614         }
615     }
616     
617     private static int getIndent (TokenSequence ts) {
618         if (ts.token ().id ().name ().equals ("js_whitespace")) {
619             String JavaDoc w = ts.token ().text ().toString ();
620             int i = w.lastIndexOf ('\n');
621             if (i >= 0)
622                 w = w.substring (i + 1);
623             i = w.lastIndexOf ('\r');
624             if (i >= 0)
625                 w = w.substring (i + 1);
626             return w.length ();
627         }
628         return 0;
629     }
630     
631     private static String JavaDoc getAsText (ASTNode n) {
632         if (n == null) return "";
633         return n.getAsText ();
634     }
635 }
636
Popular Tags