Skip to content

Instantly share code, notes, and snippets.

@jdtsmith
Last active June 29, 2024 12:30
Show Gist options
  • Save jdtsmith/f41207cb0ddc7579ed648af1f69e2a0a to your computer and use it in GitHub Desktop.
Save jdtsmith/f41207cb0ddc7579ed648af1f69e2a0a to your computer and use it in GitHub Desktop.
custom-buffer-local-keys
;; JD Smith 2024, based on https://www.emacswiki.org/emacs/BufferLocalKeys
(defvar-local custom-buffer-local-keys nil
"Key-bindings to be set up local to the current buffer.
A single (KEY . BINDING) cons or list of such conses, of the form
`bind-keys' accepts. Set this as a file-local variable to make
bindings local to that buffer only.")
(put 'custom-buffer-local-keys 'safe-local-variable 'consp)
(defvar-local my/custom-buffer-local-map nil)
(defun my/process-custom-buffer-local-keys ()
"Setup and enable a minor mode if custom-buffer-local-keys is non-nil."
(when (and (boundp 'custom-buffer-local-keys) custom-buffer-local-keys)
(let ((map my/custom-buffer-local-map)
(keys custom-buffer-local-keys))
(unless map
(setq map (make-sparse-keymap))
(set-keymap-parent map (current-local-map))
(use-local-map (setq my/custom-buffer-local-map map)))
(unless (consp (car keys)) (setq keys (list keys)))
(dolist (k keys) (local-set-key (kbd (car k)) (cdr k))))))
(add-hook 'hack-local-variables-hook #'my/process-custom-buffer-local-keys)
@jdtsmith
Copy link
Author

jdtsmith commented Jun 28, 2024

Interesting, thanks for sharing that. I came up with a simplified version based on these ideas.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment