I've written a function that recenters the point each time it makes a long jump and I added it to the hook window-scroll-functions. The length of the jump is determined by comparing the return value of (line-number-at-pos (window-end)) to that of (line-number-at-pos (window-end nil 'update)), where the former holds the line number at the window-end position before the jump, and the latter after the jump.

The problem is that window-scroll-functions runs also when I change the buffer displayed by the current window. In that case (line-number-at-pos (window-end)) returns the line number at the window-end position of the previous buffer, and I can't figure out which one it was because (ref.):

At the time of the call, the display-start position of the argument window is already set to its new value, and the buffer to be displayed in the window is set as the current buffer.

If the window-end of the previous buffer and the new one differ enough, my recentering function gets called even though it shouldn't.

How can I find out whether it was a buffer change that triggered window-scroll-functions?


One way to do it is by comparing the current-time with the buffer-display-time. If the gap is small enough it means it was most likely a buffer change that ran the hook.

(defun my-test-scroll-or-buffer-change (window _window-start-after)
  (with-selected-window window
    (if (> 0.001 (float-time (time-subtract (current-time) buffer-display-time)))
        (message "It was a buffer change")
      (message "it was a scroll"))))

(add-hook 'window-scroll-functions #'my-test-scroll-or-buffer-change)

Not very pretty but it seems to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.