Next: , Previous: , Up: Customisation  


3.5: The Keyboard

Q3.5.1: How can I bind complex functions (or macros) to keys?

As an example, say you want the paste key on a Sun keyboard to insert the current Primary X selection at point. You can accomplish this with:

(define-key global-map [f18] 'x-insert-selection)

However, this only works if there is a current X selection (the selection will be highlighted). The functionality I like is for the paste key to insert the current X selection if there is one, otherwise insert the contents of the clipboard. To do this you need to pass arguments to x-insert-selection. This is done by wrapping the call in a ’lambda form:

(global-set-key [f18]
  (lambda () (interactive) (x-insert-selection t nil)))

This binds the f18 key to a generic functional object. The interactive spec is required because only interactive functions can be bound to keys.

For the FAQ example you could use:

(global-set-key [(control ?.)]
  (lambda () (interactive) (scroll-up 1)))
(global-set-key [(control ?;)]
  (lambda () (interactive) (scroll-up -1)))

This is fine if you only need a few functions within the lambda body. If you’re doing more it’s cleaner to define a separate function as in question 3.5.3 (see Q3.5.3).