Emacs: A bufferp exercise

Inside Emacs at (info "(eintr)Buffer Exercises") there is the following exercise:

Use ‘if’ and ‘get-buffer’ to write a function that prints a message telling you whether a buffer exists.

In Emacs Lisp there is bufferp to do just that, but it is nice to have a go at one’s own version of it as an exercise. My result:

(defun exercise-bufferp (buffer)
"If the requested buffer exists, say that it exists. If not, say that
it does not exist."
(interactive "B")
(if (get-buffer buffer)
    (message "The buffer exists :)")
  (message "The buffer does not exist :(")))

Explanation line by line:
1. Begins defining the function, gives it a name and also names its argument.
2-3. Documentation.
4. Makes the function interactive, i.e. makes the function into an M-x command. “B” means the argument will be treated as buffer names, accepting also buffer names that do not exist.
5. Uses if and get-buffer as requested in the exercise.
6. Message for then event.
7. Message for else event.

Leave a Reply

Your email address will not be published. Required fields are marked *