Skip to content

Instantly share code, notes, and snippets.

@lesliesrussell
Created January 20, 2024 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lesliesrussell/0befc9b479dfc0e227be3fd58c540ab8 to your computer and use it in GitHub Desktop.
Save lesliesrussell/0befc9b479dfc0e227be3fd58c540ab8 to your computer and use it in GitHub Desktop.
temporarily rebind a key with automatic restore
(defun my-temporary-bind-key-with-restore ()
"Prompt for a register, a key sequence, and a command to temporarily bind the key to,
then automatically restore the original binding after a specified duration."
(interactive)
(let* ((register (read-char "Choose a register to save the current binding: "))
(key (read-key-sequence "Enter the key sequence to bind: "))
(original-command (key-binding key))
(new-command (read-command "Enter the command to bind to the key: "))
(duration (read-number "Enter the duration in seconds for the temporary binding: ")))
;; Save the original key binding to the register
(set-register register (format "%S" (cons key original-command)))
;; Set the new temporary binding
(global-set-key key new-command)
(message "Temporarily bound %s to %s for %d seconds. Original binding saved in register '%c'"
key new-command duration register)
;; Schedule to restore the original binding
(run-at-time duration nil
`(lambda ()
(let ((stored-value (get-register ,register)))
(when stored-value
(let ((key-command-pair (read stored-value)))
(global-set-key ,key (cdr key-command-pair))
(message "Restored command %s to key %s from register '%c'"
(cdr key-command-pair) ,key ,register))))))))
(global-set-key (kbd "C-c l") 'my-temporary-bind-key-with-restore)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment