Created
January 20, 2024 13:23
-
-
Save lesliesrussell/0befc9b479dfc0e227be3fd58c540ab8 to your computer and use it in GitHub Desktop.
temporarily rebind a key with automatic restore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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