1

I'm trying to write some buffer switching function (which in itself may be a fool's errand, but I digress...) - and it looks a little like this

(defun swk--quit-buffer (original-buffer)
  (switch-to-buffer (original-buffer))
  (kill-buffer "*tmp*")
  (local-unset-key "q"))

(defun swk-switcheroo ()
  (interactive)
  (let ((temp-buf-name "*tmp*")
        (current-buffer-name (buffer-name)))
    (get-buffer-create temp-buf-name)
    (switch-to-buffer temp-buf-name)
    (local-set-key "q" (lambda ()
                         (interactive)
                         (swk--quit-buffer current-buffer-name)))))

My aim is to be able to temporarily bind "q" to this window, to simulate special-mode's "quittable" buffer. Sure enough, the "q" key works once, but I get the message:

Symbol's value as variable is void current-buffer-name

Ideally, I want to replace the current buffer with the result of invoking swk-switcheroo - and then reinstate the original buffer when the user presses "q".

4

You're tripping over dynamic binding (as opposed to lexical binding).

Your current-buffer-name is unbound at the point that your (lambda) function is executed. The let expression only binds it during the function's definition -- there's no closure to capture that value for subsequent evaluation.

One simple workaround is to use backquoting like so:

`(lambda ()
   (interactive)
   (swk--quit-buffer ',current-buffer-name))
  • so how would I go about capturing that information? is this approach non-idiomatic? i've taken a look at save-excursion and display-buffer - perhaps they are better alternatives? – sunwukung Aug 2 '15 at 22:10
  • @sunwukung Since Emacs 24, the idiomatic way would be to enable lexical binding. In earlier versions, phils' method is the best you can do. – Gilles 'SO- stop being evil' Aug 3 '15 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.