2

我想开发一个eclipse插件,需要根据文本编辑器中的光标位置做一些操作。获取光标的行位置似乎很容易,请参阅: How to get cursor position in an eclipse TextEditor

但是如何获得列位置?

4

1 回答 1

1

以下代码似乎有效:

package plugin_test.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;


/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class SampleHandler extends AbstractHandler {
    /**
     * The constructor.
     */
    public SampleHandler() {
    }

    /**
     * the command has been executed, so extract extract the needed information
     * from the application context.
     */
    public Object execute(ExecutionEvent event) throws ExecutionException {
        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;
                IDocumentProvider provider = ((ITextEditor)editor).getDocumentProvider();
                IDocument document = provider.getDocument(editor.getEditorInput());
                int line = textSelection.getStartLine();
                int column =0;
                try {
                    column = textSelection.getOffset() - document.getLineOffset(line);
                } catch (BadLocationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                MessageDialog.openInformation(
                        win.getShell(),
                        "Plugin_test",
                        "line:"+(line+1) + 
                        " column:"+ (column+1) );
            }
        }



        return null;
    }
}
于 2013-04-21T09:41:00.490 回答