如何在Eclipse文本编辑器中获取光标位置 [英] How to get cursor position in an eclipse TextEditor

查看:281
本文介绍了如何在Eclipse文本编辑器中获取光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在jface TextEditor中获取光标位置的行号和列号。我尝试了getCursorPosition()函数。但是打印时它只显示一个?。请注意,我需要编辑器中的行号和列号,而不是屏幕。
我看到有一个函数JTextArea.getCaretPosition。但是我不知道如何将文本编辑器转换为JTextArea。
另外,是否可以读取放置游标的单词?

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?

谢谢

推荐答案

从TextEditor中,您可以获取文档,文档提供者和选择。这将让您访问当前的游标偏移。

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 提供其他方法来获取开始的行(您可以从中计算列)。

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

有关更多信息,请参阅 http://wiki.eclipse.org/The_Official_Eclipse_FAQs#Text_Editors

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

这篇关于如何在Eclipse文本编辑器中获取光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆