Computered
Computered

Reputation: 490

Get text in current line when some previous lines was collapsed in my own eclipse editor

Im trying to get the text beginning of the current line to the mouse cursor.

ITextSelection textSelection= (ITextSelection) textEditor.getSelectionProvider().getSelection();
IRegion lineInfo = null;
int offsetCurrentCursor = textSelection.getOffset();
int offsetLine; // THIS IS THE VALUE THAT I WANT
try {
    int lineNumber = document.getLineOfOffset(offsetCurrentCursor);
    lineInfo = document.getLineInformation(lineNumber);
    offsetLine = lineInfo.getOffset();
} catch (BadLocationException e) {
}

StyledText styledText = (StyledText) textEditor.getAdapter(Control.class);
String currentText = "";
if (offsetLine <= offsetCurrentCursor - 1) {
    currentText = styledText.getText(offsetLine, offsetCurrentCursor - 1);
}

But the method getText of StyledText doesn't work when some previous lines are collapsed.

Another problem is that Im trying to move the cursor using StyledText.setCaretOffset(int offset) and it also doesn't work when some previous lines are collapsed.

Upvotes: 0

Views: 298

Answers (1)

greg-449
greg-449

Reputation: 111142

Use the IDocument

public String get(int offset, int length)

method to get the text.

To get from a model (document) offset to the StyledText offset AbstractTextViewer uses:

protected static int modelOffset2WidgetOffset(ISourceViewer viewer, int modelOffset) {
    if (viewer instanceof ITextViewerExtension5) {
        ITextViewerExtension5 extension = (ITextViewerExtension5) viewer;
        return extension.modelOffset2WidgetOffset(modelOffset);
    }
    return modelOffset - viewer.getVisibleRegion().getOffset();
}

To use this you need access to the text editor ISourceViewer.

Upvotes: 1

Related Questions