Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the number of open buffers / files in Emacs?

Tags:

emacs

lisp

Every now and then, I accidentally hit C-x C-c in Emacs when I'm intending to just hit C-x or C-c. This, of course, closes all open frames and buffers with no confirmation. I know that I can make Emacs prompt "Are you sure you want to exit?", but I don't want to do that all the time, which would get annoying. I just want it to do it when there are more than N files (or buffers) open.

So I'd like to bind C-x C-c to a function along the lines of:

(if (< number of open buffers n)
    (save-buffers-kill-emacs)
    (are-you-sure))

But I can't figure out how to get the number of open buffers (or the number of open frames, or the number of open files, etc).

like image 362
mike Avatar asked Dec 08 '08 19:12

mike


2 Answers

This is what I use:

(defun count-buffers (&optional display-anyway)
  "Display or return the number of buffers."
  (interactive)
  (let ((buf-count (length (buffer-list))))
    (if (or (interactive-p) display-anyway)
    (message "%d buffers in this Emacs" buf-count)) buf-count))

I stole it , but can't remember from where. from John Sturdy, who sounds like a fascinating fellow; it's available from his website.

like image 99
JasonFruit Avatar answered Sep 28 '22 08:09

JasonFruit


Also, you can consider using desktop-mode, which will automatically restore your buffers when you start Emacs again. Just add

(desktop-save-mode 1)

to your .emacs. See GNU Emacs manual or Emacswiki.

like image 36
ShreevatsaR Avatar answered Sep 28 '22 08:09

ShreevatsaR