1 19 20 package org.netbeans.modules.javadoc.search; 21 22 import org.openide.windows.TopComponent; 23 import org.openide.cookies.EditorCookie; 24 import org.openide.nodes.Node; 25 import org.openide.text.NbDocument; 26 27 import javax.swing.JEditorPane ; 28 import javax.swing.text.Document ; 29 import javax.swing.text.Element ; 30 import javax.swing.text.StyledDocument ; 31 import javax.swing.text.BadLocationException ; 32 33 34 39 final class GetJavaWord extends Object { 40 41 42 static String getCurrentJavaWord() { 43 Node[] n = TopComponent.getRegistry ().getActivatedNodes (); 44 45 if (n.length == 1) { 46 EditorCookie ec = (EditorCookie) n[0].getCookie (EditorCookie.class); 47 if (ec != null) { 48 JEditorPane [] panes = ec.getOpenedPanes (); 49 if ( panes == null ) 50 return null; 51 if (panes.length > 0) { 52 return forPane(panes[0]); 53 } 54 } 55 } 56 57 return null; 58 } 59 60 static String forPane(JEditorPane p) { 61 if (p == null) return null; 62 63 String selection = p.getSelectedText (); 64 65 if ( selection != null && selection.length() > 0 ) { 66 return selection; 67 } else { 68 69 71 Document doc = p.getDocument(); 72 Element lineRoot; 73 74 if (doc instanceof StyledDocument ) { 75 lineRoot = NbDocument.findLineRootElement((StyledDocument )doc); 76 } else { 77 lineRoot = doc.getDefaultRootElement(); 78 } 79 int dot = p.getCaret().getDot(); 80 Element line = lineRoot.getElement(lineRoot.getElementIndex(dot)); 81 82 if (line == null) return null; 83 84 String text = null; 85 try { 86 text = doc.getText(line.getStartOffset(), 87 line.getEndOffset() - line.getStartOffset()); 88 } catch (BadLocationException e) { 89 return null; 90 } 91 92 if ( text == null ) 93 return null; 94 int pos = dot - line.getStartOffset(); 95 96 if ( pos < 0 || pos >= text.length() ) 97 return null; 98 99 int bix, eix; 100 101 for( bix = Character.isJavaIdentifierPart( text.charAt( pos ) ) ? pos : pos - 1; 102 bix >= 0 && Character.isJavaIdentifierPart( text.charAt( bix ) ); bix-- ); 103 for( eix = pos; eix < text.length() && Character.isJavaIdentifierPart( text.charAt( eix )); eix++ ); 104 105 return bix == eix ? null : text.substring( bix + 1, eix ); 106 } 107 } 108 } 109 | Popular Tags |