Afarfly
Afarfly

Reputation: 59

How to get the selected line range of NSTextView?

How to get the selected line range of NSTextView?

Upvotes: 4

Views: 4456

Answers (2)

Afarfly
Afarfly

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

CRD
CRD

Reputation: 53000

An outline algorithm for you:

  1. get the selection - selectedRange
  2. create a range of length 1 covering the last char of the selection
  3. use lineRangeForRange to obtain a range for the characters making up the line the last char of the selection is in.
  4. now work backwards and count - you've got the range of the line containing the last char of the selection, make a range for the last char of the preceding line and use 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.
  5. During the above for every line range you produce check if the starting location of the selection is in that line. Note the current line count - which started at zero for the line containing the last char of the selection and is increasing as you progress to the start of the text. When the iteration of (4) is finished simple math gives you the line number of the first char.

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

Related Questions