Find Cursor Line # in a NSTextView

I need to find the linenumber the insertion point in on in an NSTextView
this code here works except for one situation :frowning:

fileprivate func cursorPosition(textView:NSTextView) -> Int {
	let layoutManager       = textView.layoutManager
	var lineNum             = 0
	var index               = 0
	var lineRange           = NSRange()
	let numberOfGlyphs      = layoutManager!.numberOfGlyphs
	let insertionPointIndex = textView.selectedRanges.first?.rangeValue.location

	while index < numberOfGlyphs {
		lineNum  += 1
		layoutManager!.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
		if lineRange.contains(insertionPointIndex!) { break }
		index = NSMaxRange(lineRange)
	return lineNum

The problem is if the caret in in the 1st postion of the LAST line, and that line is blank
then it reports the previous line. As the cursor is “technically” past the last character in the file, but none of the metrics above seem to be able to indicate that

Added this code before the RETURN

if numberOfGlyphs == insertionPointIndex && numberOfGlyphs>0 {
    let lastChar = layoutManager!.cgGlyph(at: insertionPointIndex!-1)
    if lastChar == 65535 { lineNum+=1 }

yer welcome for the hint :slight_smile:

I said THANK YOU on the forum didn’t I???
If not, then THANK YOU! :sunglasses:

On discord I think you did

Its still and odd edge case that youd think would be easier to detect than this but it is what it is :man_shrugging:

I agree… but at least our back and forth earlier today lead to a solution… so Thanks again.

This is all going toward improvements in the Morpho UI