繁体   English   中英

如何在eclipse TextEditor中获取光标列的位置

[英]How to get cursor column location in an eclipse TextEditor

我想开发一个eclipse插件,需要根据texteditor中的光标位置进行一些操作。 看起来很容易获得光标的行位置,请参阅: 如何在Eclipse TextEditor中获得光标位置

但是如何获取列的位置呢?

以下代码似乎有效:

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM