6

I'm writing some code where I have to identify the command for the last key pressed. Sometimes I need to look up a combination of this key with another one. I use the key-binding function for that. It works most of the time but not for all keys. For example it does not work for the backspace key:

(progn
  (read-key)
  (key-binding (vector last-input-event))) ;; > nil for backspace

I can work around this by checking for backspace manually but I wonder if there is a more reliable way that works for all/most situations?

I use last-input-event because it is after exiting a keymap through the default binding [t].

Edit:

Based on the accepted answer I'm using something like the following which seems to work very well:

(progn
  (read-key)
  (key-binding (kbd (edmacro-format-keys (vector last-input-event)))))
5
  • Maybe you can find the info you need in the last-command variable: gnu.org/software/emacs/manual/html_node/eintr/…
    – Tyler
    May 25, 2016 at 0:29
  • @Tyler Thanks, unfortunately that does not work for my case, because the commands I search for were not invoked before.
    – clemera
    May 25, 2016 at 7:04
  • Why not just (key-binding (vector (read-char))) ? It looks like (vector last-input-event) doesn't always hold a valid key representation, at least for some function keys such as backspace, tab and return
    – xuchunyang
    May 25, 2016 at 12:18
  • @xuchunyang The code in my question is a contrived example I have to use last-input-event in my case because there is no manual invoked query for the key. I have edited the question accordingly.
    – clemera
    May 25, 2016 at 20:13
  • You could look at (recent-keys t) and the definition of view-lossage.
    – Tobias
    May 25, 2016 at 20:46

2 Answers 2

3

You can repurpose part of the kbd-macro infrastructure for this, specifically edmacro-format-keys. It already handles a lot of edge cases for you. For example:

(edmacro-format-keys (kbd "DEL") t) 
=> "DEL         ;; backward-delete-char-untabify"

and

(edmacro-format-keys (kbd "C-x C-s") t)
=> "C-x C-s         ;; save-buffer"
0
0

backspace and a lot of other keys are function keys for which, the event is a symbol so there is nothing in the keymaps for it.

(progn
  (read-key)
  (cond
    ((symbolp last-input-event) last-input-event)
    (t (key-binding (vector last-input-event)))))

The above still doesn't get you the function for the symbol of the function key.

(let (( key (read-key-sequence "hit a key:")) 
     (message "key %s was fun %s " key ( key-binding key t)))

But that uses read-key-sequence and it seems like you want to use last-input-event. Maybe take a look at the definition of describe-key in help.el

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.