Krishnaveni
Krishnaveni

Reputation: 809

get the position of cursor from the open editor

I have a plugin(eclipse) which will add a code snippet to the current cursor position in the java class that is open. I get the cursor position using the below code:

final ITextSelection selection = (ITextSelection) editorPart.getEditorSite().getSelectionProvider().getSelection();
final ITextEditor editor = (ITextEditor) editorPart.getAdapter(ITextEditor.class);
final IDocumentProvider documentProvider = editor.getDocumentProvider();
final IDocument document = documentProvider.getDocument(editor.getEditorInput());
final String finalSnippet = snippet.trim();
document.replace(selection.getOffset(), 0, finalSnippet);

When i invoke my plugin from a saved java class i get the correct position of the cursor. But if i make any changes in the java class, and invoke the plugin without saving the java class, the cursor position is wrong. Looks like. the code above considers the saved copy of the java class and calculates the position and not the current copy that is open in the editor.

I get the editor object with the below code:

editorPart = this.window.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();

Is there a way to get the position(line and column) of the cursor exactly as in the editor, even if the class is saved or not.

Upvotes: 0

Views: 1360

Answers (1)

Syam
Syam

Reputation: 1212

You can try calling editor.getAdapter(ITextEditor.class) and then casting it to a StyledText then get the cursor position from that StyledText#getCaretOffset().

See some other link also :
How to get cursor position in an eclipse TextEditor
Eclipse-plugin how to get current text editor corsor position

Upvotes: 2

Related Questions