A smarter alternative to delete-window?

冷暖自知 提交于 2019-12-04 15:01:31
(defun delete-extra-windows ()
  (interactive)
  (let* ((selwin  (selected-window))
         (buf     (window-buffer selwin)))
    (walk-windows (lambda (ww)
                    (unless (eq ww selwin)
                      (when (eq (window-buffer ww) buf)
                        (delete-window ww))))
                  'NO-MINI 'THIS-FRAME)))

I added quit-window (normally bound to q in non-self-insert - AKA special - buffers) 15 years ago to solve a similar problem. You can try it or its sibling quit-windows-on.

Your specification of what you wanted is not clear. You said "delete a window only if the buffer exists already in another". That means do not delete the window if the buffer does not exist in another window. Yet you also said "kill the buffer and the window if it is the only instance of the buffer in a window", which contradicts the first requirement.

I guess by "delete a window only if..." you really meant "delete only the window (not also the buffer) if...".

(defun delete-window-maybe-kill-buffer ()
  "Delete selected window.
If no other window shows its buffer, kill the buffer too."
  (interactive)
  (let* ((selwin  (selected-window))
         (buf     (window-buffer selwin)))
    (delete-window selwin)
    (unless (get-buffer-window buf 'visible) (kill-buffer buf))))
Zhro

This is the behavior I was looking for. Thank you for helping with the basic function layour and logic. Elisp is still very confusing to work with and I appreciate help with getting through the rough spots.

See the code somment which explains the behavior. You should also be able to understand it directly from the source.

I've up-voted your previous answer which includes the bulk of the code I used.

;;; Delete the selected window without killing the buffer if the buffer is open
;;; in another; otherwise close the window and its buffer. If called on the
;;; last visible window then the buffer will simply be killed and replaced by
;;; the next available buffer.
(defun delete-window-maybe-kill-buffer ()
  "Delete selected window.
If no other window shows its buffer, kill the buffer too."
  (interactive)
  (let* ((selwin (selected-window))
         (buf (window-buffer selwin)))

    (if (> (length (window-list)) 1)
        (delete-window selwin)
      (unless (get-buffer-window buf 'visible) (kill-buffer buf))
      (kill-buffer buf))))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!