1 package net.sourceforge.phpeclipse.wiki.velocity;
3 import java.text.BreakIterator;
5 import org.eclipse.jface.text.IDocument;
6 import org.eclipse.jface.text.IRegion;
7 import org.eclipse.jface.text.ITextSelection;
8 import org.eclipse.ui.IEditorPart;
9 import org.eclipse.ui.texteditor.IDocumentProvider;
10 import org.eclipse.ui.texteditor.ITextEditor;
12 public class EditorText {
13 private IEditorPart targetEditor = null;
15 String selection = null;
19 public EditorText(IEditorPart targetEditor) {
20 this.targetEditor = targetEditor;
29 * @return Returns the selection.
31 public String getSelection() {
32 if (selection == null) {
33 selection = findSelectedText();
34 if (selection == null) {
43 * The selection to set.
45 public void setSelection(String selection) {
46 this.selection = selection;
50 * @return Returns the text.
52 public String getText() {
60 public void setText(String text) {
64 public String findSelectedText() {
65 String selectedText = null;
66 ITextSelection textSelection = (ITextSelection) targetEditor.getEditorSite().getSelectionProvider().getSelection();
68 selectedText = textSelection.getText();
69 if (selectedText == null || selectedText.trim().length() == 0) {
70 selectedText = findWord(textSelection);
75 private String findWord(ITextSelection textSelection) {
76 IDocumentProvider documentProvider = ((ITextEditor) targetEditor).getDocumentProvider();
77 IDocument document = documentProvider.getDocument(targetEditor.getEditorInput());
78 int caretPosition = textSelection.getOffset();
80 IRegion line = document.getLineInformation(document.getLineOfOffset(caretPosition));
81 String currentLine = document.get(line.getOffset(), line.getLength());
82 int positionInLine = caretPosition - line.getOffset();
83 return findWordAt(positionInLine, currentLine);
84 } catch (Exception e) {
89 private String findWordAt(int pos, String source) {
90 BreakIterator boundary = BreakIterator.getWordInstance();
91 boundary.setText(source);
92 int end = boundary.following(pos);
93 int start = boundary.previous();
94 return source.substring(start, end);