Subject: bug#29999: `initial-buffer-choice' function can result in duplicate buffer display

From: David Beswick <[email-masked]>
Date: Sat, 6 Jan 2018 11:36:40 +1100

Hello, just a minor bug relating to the behaviour of startup.el's 
`command-line-1' and the `initial-buffer-choice' variable. When an 
`initial-buffer-choice' function returns the head of the 
`displayable-buffers' list in `command-line-1' then Emacs starts with 
that same buffer visited in two windows. I would expect it should only 
be shown in a single window.

To be concrete, I ran into this behavior as on startup I wanted to 
display a particular buffer that I create except when a file is given on 
the command line. In that case I want to visit the given file instead.

The behavior can be reproduced by creating a file `bug-init.el':

(require 'seq)
(setq initial-buffer-choice
       (lambda () (seq-some (lambda (b)
                              (with-current-buffer b
                                (and buffer-file-name b)))
                            (buffer-list))))

And then running this command:

$ emacs -Q -l bug-init.el bug-init.el

On startup, bug-init.el will be visited in two different windows.

My fix:

---
  lisp/startup.el | 9 +++++++--
  1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/lisp/startup.el b/lisp/startup.el
index 2855e7c31c..cef9108cdf 100644
--- a/lisp/startup.el
+++ b/lisp/startup.el
@@ -2486,7 +2486,12 @@ command-line-1
           (insert (substitute-command-keys initial-scratch-message))
           (set-buffer-modified-p nil))))

-    ;; Prepend `initial-buffer-choice' to `displayable-buffers'.
+    ;; Prepend `initial-buffer-choice' to `displayable-buffers'. If
+    ;; the buffer is already a member of that list then shift the
+    ;; buffer to the head of the list. The shift behavior is intended
+    ;; to prevent the same buffer being displayed in two windows when
+    ;; an `initial-buffer-choice' function happens to return the head
+    ;; of `displayable-buffers'.
      (when initial-buffer-choice
        (let ((buf
               (cond ((stringp initial-buffer-choice)
@@ -2499,7 +2504,7 @@ command-line-1
                      (error "initial-buffer-choice must be a string, a 
function, or t.")))))
          (unless (buffer-live-p buf)
            (error "initial-buffer-choice is not a live buffer."))
-        (setq displayable-buffers (cons buf displayable-buffers))))
+        (setq displayable-buffers (cons buf (delq buf 
displayable-buffers)))))

      ;; Display the first two buffers in `displayable-buffers'. If
      ;; `initial-buffer-choice' is non-nil, its buffer will be the
-- 
2.14.1