This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

buffer name as variable

5 posts · 6223 views

I am working through the FSF text: An Introduction to Programming in Emacs Lisp. I am having some trouble with the following buffer exercise:
Use if and get-buffer to write a function that prints a message telling you whether a buffer exists.
Here is the program I wrote:

(defun buf-exists (bufpos)
"tests to see if the buffer named bufpos exists"
(interactive)
(save-excursion
(if (get-buffer bufpos))
(message "%s def exists" bufpos)
(message "sorry there is no buffer named %s" bufpos)))


It fails for some reason to bind the named buffer passed as an argument to the variable bufpos. Any Advice?? THanks!

Re: buffer name as variable

There are two problems with this function. One, the interactive form doesn't match the number of arguments. You need argument designator for every non-optional function argument, in this case something like "M". Second, which would be very visible if the code was indented, the two MESSAGE forms are outside the scope of the IF form. Remember, Lisp is supposed to written with parentheses, but read by indentation.

This is obviously wrong:
(defun buf-exists (bufpos)
  "tests to see if the buffer named bufpos exists"
  (interactive)
  (save-excursion
    (if (get-buffer bufpos))
    (message "%s def exists" bufpos)
    (message "sorry there is no buffer named %s" bufpos)))
and should be:
(defun buf-exists (bufpos)
  "tests to see if the buffer named bufpos exists"
  (interactive "M")
  (save-excursion
    (if (get-buffer bufpos)
        (message "%s def exists" bufpos)
      (message "sorry there is no buffer named %s" bufpos))))

Re: buffer name as variable

Yes, those are some needed changes, but the function still does not work. If for example I type:

(buf-exists *scratch*)

and try to evaluate, I get the error (void-variable *scratch*)

Re: buffer name as variable

rubing wrote:(buf-exists *scratch*)
Standard Lisp evaluation rules mean that when the first element in the form is a standard function, first the remaining elements are evaluated to obtain the arguments to be passed to a function. Symbols, which is what '*scratch*' is are treated as variables, and evaluating them means obtaining the value of the variable, which in this case is, as the error message tells you, non-existent.

In any case, buffers are not named with symbols, but with strings.
(buf-exists "*scratch*")
works.

Re: buffer name as variable

rubing wrote:Yes, those are some needed changes, but the function still does not work. If for example I type:

(buf-exists *scratch*)

and try to evaluate, I get the error (void-variable *scratch*)
That's because *scratch* doesn't exist. Put it in quotes.