Search code examples
emacskey-bindings

File-specific key-binding in emacs


Is it possible to define file specific key-bindings in emacs? I suppose it would be possible to create a minor mode and have it loaded when the particular file is open but for only one key-binding that seems overkill.


Solution

  • If you combine the code to local-set-key and Buffer-locally overriding minor-mode key bindings in Emacs then you could end up with something like this:

    (defun my-buffer-local-set-key (key command)
      (interactive "KSet key buffer-locally: \nCSet key %s buffer-locally to command: ")
      (let ((oldmap (current-local-map))
            (newmap (make-sparse-keymap)))
        (when oldmap
          (set-keymap-parent newmap oldmap))
        (define-key newmap key command)
        (use-local-map newmap)))
    

    and then, as per Barmar's answer:

    ;; Local Variables:
    ;; eval: (my-buffer-local-set-key (kbd "C-c C-c") 'foo)
    ;; End:
    

    Note that minor mode maps take precedence over the local map.