Is there a built-in variable which gives the last inserted character of a buffer (inserted by self-insert-command)? Note that the cursor is not necessarily at the place of the last insertion.

If there is not such a variable, any other solution for defining a variable which determines this character would be helpful.

  • 1
    I doubt there's such a variable, however it should be trivial to achieve with a post-command-hook that tracks the argument if this-command is self-insert and checks for this-command-keys to figure out what key was hit to insert the character. – wasamasa Feb 4 '15 at 9:13

Here's a solution implementing what I've suggested in my earlier comment:

(defvar my-last-inserted-character nil
  "Last character inserted, buffer-local.")
(make-variable-buffer-local 'my-last-inserted-character)

(defun my-update-last-inserted-character ()
  (setq my-last-inserted-character (concat (this-command-keys))))

(add-hook 'post-self-insert-hook 'my-update-last-inserted-character)

It would be better to wrap it up in a minor mode before anyone gets the idea to package this.

| improve this answer | |
  • After inserting x I evaluate the expression (if (eq '(my-last-inserted-character) ?x) (message "yes") (message "no")) but it shows "no", maybe I miss something here. – Name Feb 4 '15 at 10:36
  • 1
    First, it's a variable, second, it's a string. You'd need to do (if (string= my-last-inserted-character "x") (message "yes") (message "no")). – wasamasa Feb 4 '15 at 10:41
  • Perfect, thank you very much for this nice solution. – Name Feb 4 '15 at 10:43
  • Name: Note that this works when typing keys which call self-insert-command, but not for anything else. If this still answers your question, you might like to edit the question itself to clarify that the requirement is not as general as it currently sounds. – phils Feb 5 '15 at 20:21
  • @phils Thanks for your remark and precision. I edited the question accordingly. I am also interested to know about other approaches to the problem which can applied for the cases other that self-insert-command. – Name Feb 6 '15 at 15:44

Would last-command-event in post-self-insert-hook do what you want?


(add-hook 'post-self-insert-hook (lambda () (print last-command-event)))
| improve this answer | |
  • Thanks, This shows the ascii code of the inserted character. – Name Feb 6 '15 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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