Next: , Previous: Changing Key Bindings, Up: Keymaps


22.10 Commands for Binding Keys

This section describes some convenient interactive interfaces for changing key bindings. They work by calling define-key.

People often use global-set-key in their init files (see Init File) for simple customization. For example,

     (global-set-key "\C-x\C-\\" 'next-line)

or

     (global-set-key [?\C-x ?\C-\\] 'next-line)

or

     (global-set-key [(control ?x) (control ?\\)] 'next-line)

redefines C-x C-\ to move down a line.

     (global-set-key [M-mouse-1] 'mouse-set-point)

redefines the first (leftmost) mouse button, typed with the Meta key, to set point where you click.

Be careful when using non-ascii text characters in Lisp specifications of keys to bind. If these are read as multibyte text, as they usually will be in a Lisp file (see Loading Non-ASCII), you must type the keys as multibyte too. For instance, if you use this:

     (global-set-key "ö" 'my-function) ; bind o-umlaut

or

     (global-set-key ?ö 'my-function) ; bind o-umlaut

and your language environment is multibyte Latin-1, these commands actually bind the multibyte character with code 2294, not the unibyte Latin-1 character with code 246 (M-v). In order to use this binding, you need to enter the multibyte Latin-1 character as keyboard input. One way to do this is by using an appropriate input method (see Input Methods).

If you want to use a unibyte character in the key binding, you can construct the key sequence string using multibyte-char-to-unibyte or string-make-unibyte (see Converting Representations).

— Command: global-set-key key definition

This function sets the binding of key in the current global map to definition.

          (global-set-key key definition)
          ==
          (define-key (current-global-map) key definition)
     
— Command: global-unset-key key

This function removes the binding of key from the current global map.

One use of this function is in preparation for defining a longer key that uses key as a prefix—which would not be allowed if key has a non-prefix binding. For example:

          (global-unset-key "\C-l")
              => nil
          (global-set-key "\C-l\C-l" 'redraw-display)
              => nil
     

This function is implemented simply using define-key:

          (global-unset-key key)
          ==
          (define-key (current-global-map) key nil)
     
— Command: local-set-key key definition

This function sets the binding of key in the current local keymap to definition.

          (local-set-key key definition)
          ==
          (define-key (current-local-map) key definition)
     
— Command: local-unset-key key

This function removes the binding of key from the current local map.

          (local-unset-key key)
          ==
          (define-key (current-local-map) key nil)