What does Emacs describe-key expect for input?

Viewed 97

I'm in Emacs' *scratch* and I try

(describe-key "C-x C-f")

and I get back

"C - x SPC C - f is undefined"

Obviously, it doesn't recognize my C-x C-f shorthand. What does it expect? The documentation

Display documentation of the function invoked by KEY. KEY can be any kind of a key sequence; it can include keyboard events, mouse events, and/or menu events. When calling from a program, pass KEY as a string or a vector.

doesn't elaborate on how that string or vector should be entered. What do I need to give it to work?

2 Answers

You need to specify it as (describe-key "\C-x\C-f") or (describe-key (kbd "C-x C-f")).

if you call C-h f kbd, you'll get:

(kbd KEYS)

Convert KEYS to the internal Emacs key representation. KEYS should be a string in the format returned by commands such as ‘C-h k’ (‘describe-key’).

This is the same format used for saving keyboard macros (see ‘edmacro-mode’).

You need to specify the keys exactly. "C-x C-f" is a string consisting of the capital letter C, a dash, a lower case x, a space etc.: it's a description of what you press.

What you really press is [24 6] a vector of two chars (chars are represented as integers internally and 24 and 6 are the integers representing Control-x and Control-f resp). Another way to describe the vector of these two chars is as a string consisting of two chars: "\C-x\C-f" is one way, as Alex Ott points out in his answer; equivalently "\x18\x6" uses the hexadecimal values of 24 and 6 resp; or "\030\006" uses the octal values.

But we'd rather use the description "C-x C-f", so (as Alex Ott points out in his answer again) kbd translates from the description to the actual sequence of chars:

(kbd "C-x C-f") --> "^X^F"

which is actually two characters: Control-x and Control-f. The lisp printer uses the caret representation to indicate them, so it looks like four characters in between the quotes, but that is just how they appear: if you do the above in your *scratch* buffer, put the cursor on the left quote and press right arrow or C-f on them, you'll see that there are only two characters in between the quotes.

All of this and more is explained in the GNU Emacs Lisp manual, in the Character Type section and its subsections.

Related