Moved Google and Koders Search to the wiki plugin
[phpeclipse.git] / archive / net.sourceforge.phpeclipse.wiki / src / net / sourceforge / phpeclipse / wiki / velocity / EditorText.java
1 package net.sourceforge.phpeclipse.wiki.velocity;
2
3 import java.text.BreakIterator;
4
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;
11
12 public class EditorText {
13   private IEditorPart targetEditor = null;
14
15   String selection = null;
16
17   String text = null;
18
19   public EditorText(IEditorPart targetEditor) {
20     this.targetEditor = targetEditor;
21   }
22
23   public void clear() {
24     selection = null;
25     text = null;
26   }
27
28   /**
29    * @return Returns the selection.
30    */
31   public String getSelection() {
32     if (selection == null) {
33       selection = findSelectedText();
34       if (selection == null) {
35         selection = "";
36       }
37     }
38     return selection;
39   }
40
41   /**
42    * @param selection
43    *          The selection to set.
44    */
45   public void setSelection(String selection) {
46     this.selection = selection;
47   }
48
49   /**
50    * @return Returns the text.
51    */
52   public String getText() {
53     return text;
54   }
55
56   /**
57    * @param text
58    *          The text to set.
59    */
60   public void setText(String text) {
61     this.text = text;
62   }
63
64   public String findSelectedText() {
65     String selectedText = null;
66     ITextSelection textSelection = (ITextSelection) targetEditor.getEditorSite().getSelectionProvider().getSelection();
67
68     selectedText = textSelection.getText();
69     if (selectedText == null || selectedText.trim().length() == 0) {
70       selectedText = findWord(textSelection);
71     }
72     return selectedText;
73   }
74
75   private String findWord(ITextSelection textSelection) {
76     IDocumentProvider documentProvider = ((ITextEditor) targetEditor).getDocumentProvider();
77     IDocument document = documentProvider.getDocument(targetEditor.getEditorInput());
78     int caretPosition = textSelection.getOffset();
79     try {
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) {
85     }
86     return null;
87   }
88
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);
95   }
96 }