4
votes

I'm new to emacs lisp. I'm wondering if it's possible in elisp to listen on keyboard events while typing in a buffer. I read about the documentation of read-key-sequence / read-key-sequence-vector / read-event / read-key, turns out these commands block the buffering entering flow because when invoked, subsequent key strokes doesn't show up in the buffer. E.g. If I type "go" into current buffer then call read-key-sequence then type "o", the second "o" is treated as a command sequence not character of the buffer content text.

Though I may have found a way to work around this, that's to insert back the key stroke into the buffer programmatically:

(catch 'break
(while 
  (progn
    (let
        ((strokes (read-key-sequence-vector nil)))
        (if 
            (equal strokes [27 27 27])
            (throw 'break nil)
            (insert strokes)))
    t)))

I would prefer to see if there are better ways to achieve this. It would be nice if elisp can do the event driven stuff like in javascript

 someObject.addEventListener('keydown', function (e) { ... })

That's only my hope of course. :) Thanks.

1
What are you trying to achieve? Typically, you either bind keys or keysequences to functions, or you could use event hooks like pre-command-hook and post-command-hook to do "magical" things. - Lindydancer
I'm trying to attach some behaviors on every key stroke when typing stuff in current buffer; the behaviors can be anything - like showing something interesting in the Message buffer. The key is I don't want these behavior to interrupt the normal typing flow - no switching back to the mini-buffer. I'll look at the pre- and post- hooks. Thanks. - Shawn

1 Answers

4
votes

If I understand what you're doing, you should look at post-self-insert-command-hook. This will allow you to run your function after every regular key-press (excluding keyboard shortcuts).