Reputation: 59
How to get the selected line range of NSTextView
?
Upvotes: 4
Views: 4456
Reputation: 59
First, get the selected range through [textView selectedRange]
Then you can get the line range through - (NSRange)lineRangeForRange:(NSRange)range
of [textView string]
NSRange sel = [textView selectedRange];
NSString *viewContent = [textView string];
NSRange lineRange = [viewContent lineRangeForRange:NSMakeRange(sel.location,0)];
Upvotes: 2
Reputation: 53000
An outline algorithm for you:
selectedRange
lineRangeForRange
to obtain a range for the characters making up the line the last char of the selection is in.lineRangeForRange
to find the range for the preceding line. Repeat this process until you reach the start of the text. You'll have the line number of the last character in the original selection.Of course you could work the other way around - start with the line range for the first char in the text and work forward. For every line checking whether the start/end of the selection is in that line, stopping when you've found the line containing the end of the selection.
For code which does the reverse - given a range of lines it produces a selection to cover them - see Apple's TextEdit code sample, look at LinePanelController.m
. Though this is doing the opposite of what you want reading it will show how the above mentioned methods work.
HTH.
Upvotes: 5