get line number within a eclipse Plugin

柔情痞子 提交于 2019-12-04 21:07:36

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.

eactor

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());
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!