The schematic algorithm for you:
- get selection -
selectedRange - create a range of length 1 covering the last char of choice
- use
lineRangeForRange to get the range for the characters that make up the string the last char is in. - now work back and count - you have a row range containing the last char to select, enter a range for the last char of the previous row and use
lineRangeForRange to find the range for the previous row. Repeat this process until you reach the beginning of the text. You will have the line number of the last character in the original selection. - During the above, for each row range, you check if the starting position of the selection is in this row. Notice the current line count, which starts at zero for the line containing the last char of the selection, and increases as you move to the beginning of the text. When iteration (4) is completed, simple math gives the line number of the first char.
Of course, you could work the other way around - start with a range of lines for the first char in the text and continue. For each line that checks whether the start / end of a selection is on that line, stop when you find a line containing the end of the selection.
For code that does the opposite - if a series of lines is specified, it creates a selection to cover them - see Apple TextEdit code example , see LinePanelController.m . Although this does the opposite of what you want to read, it will show how the above methods work.
NTN.
source share