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
  • 75,699
  • 9
  • 109
  • 225
  • 1
    Does this answer your question? [What is the difference between a function and a command?](https://emacs.stackexchange.com/questions/3555/what-is-the-difference-between-a-function-and-a-command) – Drew Aug 08 '20 at 21:26
  • 1
    Your `global-set-key` needs to bind the key to a **command**. You're trying to bind it to a list of a symbol and a string. See ["command" in the glossary](https://www.gnu.org/software/emacs/manual/html_node/elisp/What-Is-a-Function.html). – Drew Aug 08 '20 at 21:29
  • @Drew Very helpful, thank you. ... "To make a function bar available as a command you can wrap it in a custom interactive function (foo)" – breathe_in_breathe_out Aug 08 '20 at 21:36

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
  • 18,826
  • 5
  • 37
  • 118
  • 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