Subject: Re: bug#73627: 29.3; window-main-window: Discrepancy between behaviour and docstring

From: martin rudalics <[email-masked]>
Date: Sat, 5 Oct 2024 16:37:50 +0200

>> To reproduce from emacs -Q, evaluate in the scratch buffer:
 >>
 >> (display-buffer-in-side-window
 >>    (get-scratch-buffer-create)
 >>    '((side . left)))
 >> (split-window (frame-root-window) nil 'below)
 >> (window-main-window)
 >>
 >> Observe that (window-main-window) returns the selected window. However, the
 >> window that was created by splitting below is not a side window, and it does not
 >> descend from the selected window. This contradicts part of the docstring of
 >> window-main-window:
 >>
 >> "If FRAME has no side windows, return FRAME's root window. Otherwise, return
 >> either an internal non-side window such that all other non-side windows on FRAME
 >> descend from it, or the single live non-side window of FRAME."

This accusation is correct.

 >> Splitting a frame's root window in the presence of side windows seems to often
 >> lead to such discrepancies. I have observed such behaviour in the packages hydra
 >> (on ELPA, in its lv-window function), and shell-pop (from another package
 >> archive).
 >>
 >> Related to that: Is the following supposed to be an invariant for each frame,
 >> and should it be considered a bug when packages violate it?
 >>
 >> Invariant:
 >> There exists a window MAIN such that for all live windows WIN (other than MAIN)
 >> we have: WIN descends from MAIN if and only if it is not a side window.

It should be an invariant and it is a bug when packages (or, as in the
case at hand Emacs itself) violate it.

 >> This is something I assumed and was surprised to see violated.
 >
 > Martin, any comments?

Ferdinand is right.  'split-window' must split the frame's main window
instead of the root window.  Patch attached.  It should be OK for the
release version but I won't insist since the bug has been with us ever
since side windows exist.

Thanks for the report, martin

diff --git a/lisp/window.el b/lisp/window.el
index 006cfa19525..254814b989a 100644
--- a/lisp/window.el
+++ b/lisp/window.el
@@ -5455,6 +5455,13 @@ split-window
 	     (setq atom-root (window-atom-root window))
 	     (not (eq atom-root window)))
 	(throw 'done (split-window atom-root size side pixelwise)))
+       ;; If WINDOW's frame has a side window and WINDOW specifies the
+       ;; frame's root window, split the frame's main window instead
+       ;; (Bug#73627).
+       ((and (eq window (frame-root-window frame))
+	     (window-with-parameter 'window-side nil frame))
+	(throw 'done (split-window (window-main-window frame)
+				   size side pixelwise)))
        ;; If WINDOW is a side window or its first or last child is a
        ;; side window, throw an error unless `window-combination-resize'
        ;; equals 'side.