Subject: Re: bug#57837: 29.0.50; fit-window-to-buffer should reposition the buffer

From: Gregory Heytings <[email-masked]>
Date: Thu, 15 Sep 2022 19:34:38 +0000

>
> When the buffer is smaller than the window, move the point to the end
> and do `C-x w -` (fit-window-to-buffer).
>
> The window shrinks, but it is empty - the whole buffer is above.
>

Is that with emacs -Q?  With emacs -Q the buffer is recentered after 
fit-window-to-buffer, and half of it (with your example) is visible.  If 
you want to see the whole buffer in that case, you can one of the 
following lines to your init file:

(advice-add 'fit-window-to-buffer :before (lambda () (or (< (point) (point-max)) (previous-line))))

(advice-add 'fit-window-to-buffer :after (lambda () (enlarge-window 1)))

But that still does not guarantee that after fit-window-to-buffer the 
whole buffer will be visible, if you press C-l and repeat 
fit-window-to-buffer only the second half of the buffer is visible.  If 
you want to handle that case as well, you can use this for example:

(advice-add 'fit-window-to-buffer :after
 	    (lambda () (and (= (count-lines (point-min) (point-max)) (1- (window-height)))
 			    (or (< (point) (point-max)) (forward-line -1) t)
 			    (set-window-start nil (point-min)))))

>
> Basically, after `fit-window-to-buffer' is called, the following should 
> evaluate to t:
>
> (and (pos-visible-in-window-p (point-min))
>     (pos-visible-in-window-p (point-max)))
>

That would only be possible under the condition you mention: "when the 
buffer is smaller than the window".