2
我想開發一個eclipse插件,需要根據光標在texteditor中的位置進行一些操作。 看起來很容易得到光標的行位置,請參閱: How to get cursor position in an eclipse TextEditor如何獲取Eclipse中的光標列位置TextEditor
但是如何獲取列位置?
我想開發一個eclipse插件,需要根據光標在texteditor中的位置進行一些操作。 看起來很容易得到光標的行位置,請參閱: How to get cursor position in an 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;
}
}
我沒有這樣做了一段時間,但我記得那是尷尬的拿到X,光標的Y位置,所以你可能是正確的用這個解決方案。 – Bananeweizen 2013-04-21 19:32:16