tags:

views:

372

answers:

3

Hi,

I would like to write a function which takes action if a give buffer name already exists. For example:

(if (buffer-exists "my-buffer-name")
    ; do something
 )

Does elisp have a function that will check the for the existence of a buffer similar to how my made up "buffer-exists" function does?

Thanks

+12  A: 

From the documentation:

(get-buffer name)

Return the buffer named name (a string).
If there is no live buffer named name, return nil.
name may also be a buffer; if so, the value is that buffer.

(get-buffer-create name)

Return the buffer named name, or create such a buffer and return it.
A new buffer is created if there is no live buffer named name.
If name starts with a space, the new buffer does not keep undo information.
If name is a buffer instead of a string, then it is the value returned.
The value is never nil.
Gareth Rees
+1  A: 

If you'd like to define your hypothetical function as above, this works:

(defun buffer-exists (bufname) (not (eq nil (get-buffer bufname))))

I use this to automatically close the scratch buffer on startup, so I don't have to cycle through it in my list of buffers, as follows:

(defun buffer-exists (bufname) (not (eq nil (get-buffer bufname))))
(if (buffer-exists "scratch")  (kill-buffer "scratch"))

A: 

Gareth's answer is technically correct but isn't it faster to hit C-x b (switch to buffer), type a few letters of the name of the buffer you're looking for, and hit tab which pulls up a list of matching buffers and then just see if it is in the list?

Neil Sarkar