Close all buffers besides the current one in Emacs

2020-02-16 06:24发布

How do I close all but the current buffer in Emacs? Similar to "Close other tabs" feature in modern web browsers?

标签: emacs elisp
9条回答
我只想做你的唯一
3楼-- · 2020-02-16 06:47

From EmacsWiki: Killing Buffers:

(defun kill-other-buffers ()
    "Kill all other buffers."
    (interactive)
    (mapc 'kill-buffer 
          (delq (current-buffer) 
                (remove-if-not 'buffer-file-name (buffer-list)))))

Edit: updated with feedback from Gilles

查看更多
孤傲高冷的网名
4楼-- · 2020-02-16 06:49

There is a built in command m-x kill-some-buffers (I'm using 24.3.50) In my nextstep gui (not tried in a terminal but sure it's similar) you can then approve which buffers to kill.

查看更多
beautiful°
5楼-- · 2020-02-16 06:52

There isn't a way directly in emacs to do this.

You could write a function to do this. The following will close all the buffers:

(defun close-all-buffers ()
  (interactive)
  (mapc 'kill-buffer (buffer-list)))
查看更多
Viruses.
6楼-- · 2020-02-16 06:56

I found this solution to be the simplest one. This deletes every buffer except the current one. You have to add this code to your .emacs file

(defun kill-other-buffers ()
      "Kill all other buffers."
      (interactive)
      (mapc 'kill-buffer (delq (current-buffer) (buffer-list))))

Of course, then you use it with M-x kill-other-buffers RET or you paste the following code in the .emacs file too and then just press C-xC-b

(global-set-key (kbd "C-x C-b") 'kill-other-buffers)
查看更多
Luminary・发光体
7楼-- · 2020-02-16 07:01
 (defun only-current-buffer () 
   (interactive)
   (let ((tobe-killed (cdr (buffer-list (current-buffer)))))
     (while tobe-killed
       (kill-buffer (car tobe-killed))
       (setq tobe-killed (cdr tobe-killed)))))

It works as you expected.

And after reading @Starkey's answer, I think this will be better:

(defun only-current-buffer () 
  (interactive)                                                                   
    (mapc 'kill-buffer (cdr (buffer-list (current-buffer)))))

(buffer-list (current-buffer)) will return a list that contains all the existing buffers, with the current buffer at the head of the list.

This is my first answer on StackOverflow. Hope it helps :)

查看更多
登录 后发表回答