Search code examples
emacs

Emacs: how to bind a key tapped twice?


I am using Emacs (23) and I am binding the C-. key combination to a function:

(global-set-key (kbd "C-.") 'myfunction)

Is it possible to bind a quick "double tap" of a key? For example, I would like to call a function myfunction when typing . quickly two times.


Solution

  • There isn't anything built in, but you can use this code. Customize the variables dc-single-click-cmd and dc-double-click-cmd to be the commands you want.

    Note: this introduces a slight delay, b/c the code needs to wait for a little bit of time to determine whether the event was a single or double click.

    (defvar dc-single-click-cmd 'dc-example-single-click)
    (defvar dc-double-click-cmd 'dc-example-double-click)
    (defvar dc-click-timer nil
      "Pending single-click event.")
    (defun dc-example-single-click ()
      (interactive)
      (message "A single click just happened."))
    (defun dc-example-double-click ()
      (interactive)
      (message "Wait!  I meant double click."))
    (defun dc-click-cmd ()
      "Either kick off a single click, or a double click."
      (interactive)
      (if dc-click-timer
          (progn
            (cancel-timer dc-click-timer)
            (setq dc-click-timer nil)
            (call-interactively dc-double-click-cmd))
        (setq dc-click-timer (run-at-time (when double-click-time 
                                                (/ 1000.0 double-click-time))
                                          nil
                                          'dc-call-single-click))))
    (defun dc-call-single-click ()
      "spawn the single click"
      (setq dc-click-timer nil)
      (call-interactively dc-single-click-cmd))