8

I have been trying to get the line number and column number of the cursor position in a jface TextEditor. I tried the function getCursorPosition(). But on printing this it shows just a "?". Please note that I need the line number and column number within an editor and not with respect to the screen. I saw that there is a function JTextArea.getCaretPosition. But I dont know how to convert a text editor to JTextArea. Also, is it possible to read the word where the cursor is placed?

Thanks

Smitha
  • 81
  • 1
  • 2

1 Answers1

9

From a TextEditor, you can get the document, document provider, and selection. That will give you access to the current cursor offset.

ITextEditor editor = (ITextEditor) editorPart
        .getAdapter(ITextEditor.class);
IDocumentProvider provider = editor.getDocumentProvider();
IDocument document = provider.getDocument(editorPart
        .getEditorInput());
ITextSelection textSelection = (ITextSelection) editorPart
        .getSite().getSelectionProvider().getSelection();
int offset = textSelection.getOffset();
int lineNumber = document.getLineOfOffset(offset);

IDocument provides other methods to get the starts of lines (you can calculate the column from that).

For more information see http://wiki.eclipse.org/The_Official_Eclipse_FAQs#Text_Editors

Paul Webster
  • 10,614
  • 1
  • 25
  • 32
  • buggy since conversion is not check – Chameleon Mar 02 '13 at 09:41
  • Mind that this does not get the position of the actual caret, but of the selection. The caret can be located at either end of the selection. – Lii Apr 23 '13 at 22:11
  • 1
    Can't I actually get the position without selecting a portion in the editor? – Masud Rahman Jun 18 '14 at 01:32
  • AFAIK getSelection() returns the data structure, which is valid when the cursor is in the editor as well as when there's a selection – Paul Webster Apr 23 '15 at 16:40
  • getSelection() provides the last selection position. If you clear it and move the cursor somewhere else, you will still get the last selection position which is not related to the cursor at all. – Christian Mar 22 '18 at 12:17