问题
I'm looking for the right extension point for my plugin to access the cursor position in the editor. The aim is to provide additional information to the current code line in a plugin view. I sure it is possible, since the Outline view for example highlights the current function which I'm within. thx
回答1:
You can use textSelection.getOffset() from the pattern you've found and then use the org.eclipse.jface.text.IDocument interface to extract text from the document to do whatever analysis you want.
ITextEditor textEditor = (ITextEditor)editor;
IDocumentProvider dp = editor.getDocumentProvider();
IDocument doc = dp.getDocument(editor.getEditorInput());
IDocument has methods to convert back and forth between character offsets and lines.
回答2:
The following code does what I want
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.ISelection;
IWorkbench wb = PlatformUI.getWorkbench();
IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
IWorkbenchPage page = win.getActivePage();
IEditorPart editor = page.getActiveEditor();
if(editor instanceof ITextEditor){
ISelectionProvider selectionProvider = ((ITextEditor)editor).getSelectionProvider();
ISelection selection = selectionProvider.getSelection();
if (selection instanceof ITextSelection) {
ITextSelection textSelection = (ITextSelection)selection;
System.out.println("startline:"+textSelection.getStartLine());
}
}
来源:https://stackoverflow.com/questions/10980082/get-line-number-within-a-eclipse-plugin