get line number within a eclipse Plugin

2019-04-15 02:53发布

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

2条回答
萌系小妹纸
2楼-- · 2019-04-15 03:05

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());
    }
}
查看更多
该账号已被封号
3楼-- · 2019-04-15 03:22

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.

查看更多
登录 后发表回答