It would not be easier to determine the current position of the carriage. Having a position allows you to easily determine if the carriage is on the word (define the word as you like, for example, separated by spaces, java identifier or regular expression).
I cannot start eclipse here, but I would use the CaretListener class to detect carriage movements and thus extract the word under it. CaretEvent
specified as a parameter to the caretMoved
method will contain the offset.
CaretListener
can bind CaretListener
to the Adapter
your StyledText
component, which you can get from your EditorPart
(at the moment there is no more information, since I do not have eclipse here).
Hope this helps.
Edit: some 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() > 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 > 0 && offsetInLine < line.length()) { for (int i = offsetInLine; i >= 0; --i) { if (!Character.isSpaceChar(line.charAt(i))) { word.append(line.charAt(i)); } else { break; } } word = word.reverse(); } if (offsetInLine < line.length()) { for (int i = offsetInLine; i < line.length(); ++i) { if (i == offsetInLine) continue;
This is a simple implementation to get the word under the cursor based on the space surrounding it. To detect valid Java identifiers, etc. A more robust implementation should be used. For example, using Character.isJavaIdentifierStart
and Character.isJavaIdentifierPart
or using the library for this.
source share