0

I am reading the Intro to Lisp Programing and got to the chapter where switch-to-buffer is introduced.

I tried to bind (switch-to-buffer "*scratch*") via global-set-key

But this does not work:

(global-set-key (kbd "<S-f11>") '(switch-to-buffer "*scratch*"))

I looked at Bernt Hansens config and he defined an extra function for this.

(defun bh/switch-to-scratch ()
  (interactive)
  (switch-to-buffer "*scratch*"))

Why is this necessary?

Drew
  • 77,472
  • 10
  • 114
  • 243

1 Answers1

2

The following demonstrates the most commonly used method to define a keyboard shortcut using global-set-key. The function bh/switch-to-scratch is okay "as-is". Keep in mind that we are defining SHIFT+F11 in this example:

(defun bh/switch-to-scratch ()
  (interactive)
  (switch-to-buffer "*scratch*"))

(global-set-key (kbd "<S-f11>") 'bh/switch-to-scratch)

Alternatively, we could use the following -- keeping in mind that Emacs requires that functions activated via keyboard shortcuts be interactive, and lambda is required to make this example work:

(global-set-key (kbd "<S-f11>") (lambda () (interactive) (switch-to-buffer "*scratch*")))
lawlist
  • 19,106
  • 5
  • 38
  • 120
  • I see, thank you. Is there a "better" way or are they both equally suited? – breathe_in_breathe_out Aug 08 '20 at 21:05
  • 2
    If it is for your own setup, either way is fine. If you are developing a library for others to use, then the first method is the most common and users will expect to see something like that. That being said, I have seen popular libraries that still define a few keyboard shortcuts using the second method. When you type C-h k aka M-x describe-key, the *Help* buffer is a little cleaner looking (in my opinion) using the first method and one can still jump to where the function is defined (if so desired). – lawlist Aug 08 '20 at 21:06