0

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
  • 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
    Commented Feb 4, 2015 at 9:13

2 Answers 2

2

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.

6
  • 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
    Commented Feb 4, 2015 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
    Commented Feb 4, 2015 at 10:41
  • Perfect, thank you very much for this nice solution.
    – Name
    Commented Feb 4, 2015 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
    Commented Feb 5, 2015 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
    Commented Feb 6, 2015 at 15:44
1

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

e.g.:

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

Your Answer

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

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