get line number within a eclipse Plugin

霸气de小男生 提交于 2019-12-09 23:27:34

问题


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

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