         }
         
         // get glyph range of which line number should be drawn
-        let visibleRect = self.scrollView?.documentVisibleRect ?? textView.frame
-        let glyphRangeToDraw = layoutManager.glyphRange(forBoundingRectWithoutAdditionalLayout: visibleRect, in: textContainer)
+        let glyphRangeToDraw = layoutManager.glyphRange(forBoundingRectWithoutAdditionalLayout: textView.visibleRect, in: textContainer)
         
         // count up lines until visible
-        let undisplayedRange = NSRange(location: 0, length: layoutManager.characterIndexForGlyph(at: glyphRangeToDraw.location))
-        var lineNumber = max(string.numberOfLines(in: undisplayedRange, includingLastLineEnding: true), 1)  // start with 1
+        let firstVisibleIndex = layoutManager.characterIndexForGlyph(at: glyphRangeToDraw.location)
+        var lineNumber = string.lineNumber(at: firstVisibleIndex)
         
         // draw visible line numbers
-        var glyphCount = glyphRangeToDraw.location
         var glyphIndex = glyphRangeToDraw.location
         var lastLineNumber = 0
         

            else { return }
        
        // get start point
        let point = window.convertToScreen(NSRect(origin: event.locationInWindow, size: NSSize.zero)).origin
        let index = textView.characterIndex(for: point)
        
        // repeat while dragging

                        drawTick(y: y)
                    }
                    if !isVerticalText || lineNumber % 5 == 0 || lineNumber == 1 || isSelected ||
                        (lineRange.upperBound == length && layoutManager.extraLineFragmentTextContainer == nil)  // last line for vertical text
                    {
                        drawLineNumber(lineNumber, y: y, isBold: isSelected)
                    }
