Determining automatic scroll position in NSTextView

I have an NSTextView which uses syntax highlighting via textDidChange delegate method. Its contents are scaled using scaleUnitSquareToSize.

Automatic scrolling works correctly when user reaches the bottom of the screen and line wraps — if this happens in the middle of the document. At the end, however, the scrolling seems to jump erratically for the first couple of characters.

Causes of the issue

I've tracked down the issue to a certain call order. Normally, textDidChange: is called between NSTextView keyDown: and NSClipView _scrollTo:, but not when the line gets so long it wraps.

When typing will cause the line to wrap, the call stack looks like this (from bottom to top):

[NSTextView adjustScroll:]
[NSClipView _scrollTo:animateScroll:flashScrollerKnobs:]
[NSTextView keyDown:]

This is how it usually looks:

[NSTextView adjustScroll:]
[NSClipView _scrollTo:animateScroll:flashScrollerKnobs:]
[Document textDidChange:]
[NSTextView keyDown:]

I have no idea how keyDown and _scrollTo determine where to scroll, but it seems that at some point, the text view scale is not taken into account, or gets calculated incorrectly.

Solutions?

I've tried wrapping my syntax highlighting in textStorage.beginEditing() and .endEditing(), which kind of fixes the issue, but also causes even more scrolling glitches when pressing space or deleting backwards.

I also tried disabling adjustScroll in the text view while syntax highlighting has not yet taken place, but that, too, causes completely random jumps in scroll position, again when inserting a space or deleting.

I'm trying to figure out how and where NSTextView determines the scroll position. There is no visible method in the call stack, but there has to be a method that checks if caret is in view and how to reposition content view's bounds, right? ...... Right?

Any help or hints would be appreciated.

Determining automatic scroll position in NSTextView
 
 
Q