如何在 Eclipse TextEditor 中获取光标位置

发布于 2024-11-26 12:01:07 字数 210 浏览 3 评论 0原文

我一直在尝试获取 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?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧故 2024-12-03 12:01:07

从文本编辑器中,您可以获得文档、文档提供程序和选择。这将使您能够访问当前光标偏移量。

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文