java - 当之前的一些行在我自己的 Eclipse 编辑器中折叠时获取当前行

标签 java eclipse eclipse-plugin swt text-editor

我正在尝试获取键盘光标的当前行。

StyledText styledText = (StyledText) getAdapter(Control.class);
styledText.addCaretListener(event -> {
    try {
        IDocument document = getDocumentProvider().getDocument(getEditorInput());
        // This is the current line
        int currentLine = document.getLineOfOffset(event.caretOffset);

    } catch (BadLocationException e) {
    }
});

但是当某些先前的行折叠时, getLineOfOffset 方法不起作用。如果文档折叠,则 event.caretOffset 会发生变化。

我尝试使用此代码:

ISelectionProvider selectionProvider = ((ITextEditor)editor).getSelectionProvider();
ISelection selection = selectionProvider.getSelection();
if (selection instanceof ITextSelection) {
    ITextSelection textSelection = (ITextSelection)selection;
    return textSelection.getStartLine();
}

但是最后一个代码返回所选的旧行。我认为 addCaretListener 事件在更改行之前执行(不确定)。

即使文档在 addCaretListener 事件中折叠,如何获取当前行?

最佳答案

如果您的编辑器使用 ProjectionViewer 作为源查看器,您可以 使用 ITextViewerExtension5 widgetOffset2ModelOffset 方法:

ISourceViewer sourceViewer = getSourceViewer(); // Get your SourceViewer

StyledText styledText = sourceViewer.getTextWidget();

int docOffset = 0;
if (sourceViewer instanceof ITextViewerExtension5) {
    ITextViewerExtension5 extension = (ITextViewerExtension5)sourceViewer;
    docOffset = extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} 
else {
    int offset = sourceViewer.getVisibleRegion().getOffset();
    docOffset = offset + styledText.getCaretOffset();
}

IDocument document = sourceViewer.getDocument();

int currentLine = document.getLineOfOffset(docOffset);

(改编自 JDT JavaEditor)。

关于java - 当之前的一些行在我自己的 Eclipse 编辑器中折叠时获取当前行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30444140/

相关文章:

java - 错误: type org. osgi.util.tracker.ServiceTracker不接受参数

java - Javah工具错误: could not find class file for HelloWorld

eclipse - 使用命令行将插件安装到 Eclipse 中

java - 将应用程序设置为主启动另一个实例

java - 计算平衡系数

Android 的渐变绘图 : poor quality of screenshots in Eclipse

python - PyDev eclipse 没有显示编译错误

html - Eclipse 的 JavaDoc 编辑器,用于创建格式化文本

java - 切换 JFrame 而不更改引用

java - JDBC 模板运行缓慢