-
-
Save jdtsmith/f41207cb0ddc7579ed648af1f69e2a0a to your computer and use it in GitHub Desktop.
;; 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.") | |
;; Only include this if you trust the files you open | |
(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) |
Interesting, thanks for sharing that. I came up with a simplified version based on these ideas.
A very cool idea, that I added immediately to my emacs config. But adding custom-buffer-local-keys to safe-local-variables is questionable. This could be used to trick someone into running untrusted code. The example shows how to define a custom command inline. Just use that to prepend self-insert-command with something else and bind it to a simple letter key.
Yes you could obviously craft a malicious file that changed a common binding like SPACE
to do something nefarious, if you could convince me to download and open that file. There are many ways to do this, and I really doubt this particular custom config would invite targeted attacks.
I've added a warning comment. If you worry about this, you could change the name of the local variable to something distinct like your-initials//custom-buffer-local-keys
to limit possible misuse (and don't tell anyone the name you chose).
In
#emacs
-channel onirc.libera.chat
IRC-network,bpalmer
shared these insights: