bmargulies
bmargulies

Reputation: 100051

wrap a function in emacs lisp

In 1987, I wrote the code I'm going to paste in a moment. The mechanism used here to capture the initial function binding of switch-to-buffer doesn't work any more, resulting in infinite recursion. I guess that there's a right way to do this sort of thing now, could someone please fill me in?

(defvar *real-buffer-switcher* nil)

(defun improve-buffer-switch ()
  (if *real-buffer-switcher* nil
    (setq *real-buffer-switcher* (symbol-function 'switch-to-buffer))
    (fset 'switch-to-buffer 'better-switch-to-buffer)
    t))

;(setq *real-buffer-switcher* (symbol-function 'switch-to-buffer))

(defun better-switch-to-buffer (buffer-name &optional no-record)
  (interactive "p") ; c-u c-x b goes ahead and creates. Note that
            ; buffer-name is fraudulently named so as to permit
            ; non-interactive calls.
  ;; first, filter out the noninteractive case.
  (if (or (stringp buffer-name)
      (bufferp buffer-name))
      (funcall *real-buffer-switcher* buffer-name no-record)
    ;; interactive. Numeric arg?
    (funcall *real-buffer-switcher*
         (read-buffer "Buffer name: "
              (other-buffer (current-buffer))
              (= buffer-name 1)))))

(improve-buffer-switch)

Upvotes: 5

Views: 957

Answers (2)

bmargulies
bmargulies

Reputation: 100051

It seems that the right answer to my question is defadvice.

Upvotes: 2

Trey Jackson
Trey Jackson

Reputation: 74450

I'm not sure why the code that used to work no longer works (unless your *real-buffer-switcher* somehow got set to 'better-buffer-switcher. Is there any reason why you don't just bind C-x b the the routine you really want and leave switch-to-buffer alone?

Like so:

(defun better-switch-to-buffer (buffer-name &optional no-record)
  (interactive "p") 
  ;; interactive. Numeric arg?
  (switch-to-buffer
   (read-buffer "Buffer name: "
                (other-buffer (current-buffer))
                (= buffer-name 1))))

(global-set-key (kbd "C-x b") 'better-switch-to-buffer)

Upvotes: 3

Related Questions