Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Wouldn't it be easier to detect the caret current position. Having the position let you easily detect if the caret is on a word (define word as you like, for example space-separated, java identifier, or with a regular expression).</p> <p>I'm not able to run eclipse here, but I would use the <a href="http://help.eclipse.org/helios/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/custom/CaretListener.html" rel="nofollow">CaretListener</a> class in order to detect caret movements and thus extracting the word under it. The <code>CaretEvent</code> given as parameter to the <code>caretMoved</code> method will contain the offset.</p> <p>The <code>CaretListener</code> can be attached to the <code>Adapter</code> of your <code>StyledText</code> component, that you can get from your <code>EditorPart</code> (don't have any more info for the moment, as I don't have eclipse running here).</p> <p>Hope it helps.</p> <p>Edit: Some code.</p> <pre><code>final StyledText text = (StyledText)editorPart.getAdapter(Control.class); text.addCaretListener(new CaretListener() { public void caretMoved(CaretEvent event) { int offset = event.caretOffset; String word = findWord(offset, text); if (word.length() &gt; 0) { System.out.println("Word under caret: " + word); } } }); private String findWord(int offset, StyledText text) { int lineIndex = text.getLineAtOffset(offset); int offsetInLine = offset - text.getOffsetAtLine(lineIndex); String line = text.getLine(lineIndex); StringBuilder word = new StringBuilder(); if (offsetInLine &gt; 0 &amp;&amp; offsetInLine &lt; line.length()) { for (int i = offsetInLine; i &gt;= 0; --i) { if (!Character.isSpaceChar(line.charAt(i))) { word.append(line.charAt(i)); } else { break; } } word = word.reverse(); } if (offsetInLine &lt; line.length()) { for (int i = offsetInLine; i &lt; line.length(); ++i) { if (i == offsetInLine) continue; // duplicate if (!Character.isSpaceChar(line.charAt(i))) { word.append(line.charAt(i)); } else { break; } } } return word.toString(); } </code></pre> <p>This is simple implementation to get the word under the cursor based on space character surrounding it. A more robust implementation should be used in order to detect valid Java identifiers etc. For example using <code>Character.isJavaIdentifierStart</code> and <code>Character.isJavaIdentifierPart</code> or using a library for this.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload