1

What is the proper way to override a keybinding for a major mode so it only affects the buffer-local keymap? I thought I could use local-set-key or make-local-variable, but my attempts there affect the keymaps globally (shown below).

Is it necessary to copy the map, as done below, or create a minor mode with a different keymap? It would be nice to be able to make it a local variable if possible.

For example, say I want to have original bound to C-c C-c in the global emacs-lisp-mode-map but after calling jump-to-other-buffer I want C-c C-c to be bound to local-version only in that buffer.

(defun original ()
  (interactive)
  (message "original"))

(defun local-version ()
  (interactive)
  (message "local binding"))

;; open new buffer in emacs-lisp mode and set a local key
(defun jump-to-other-buffer ()
  (interactive)
  (with-current-buffer (get-buffer-create "*test1*")
    (emacs-lisp-mode)
    ;; These change bindings in all elisp buffers
    ;; (make-local-variable 'emacs-lisp-mode-map)
    ;; (define-key emacs-lisp-mode-map (kbd "C-c C-c") 'local-version)
    ;; (local-set-key (kbd "C-c C-c") 'local-version)
    (let ((overriding-local-map (copy-keymap emacs-lisp-mode-map)))
      (define-key overriding-local-map (kbd "C-c C-c") 'local-version)
      (use-local-map overriding-local-map))
    (pop-to-buffer (current-buffer))))

;; default binding in elisp buffers
(define-key emacs-lisp-mode-map (kbd "C-c C-c") 'original)
Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • Does http://stackoverflow.com/a/21493693 help? This looks close enough to being a duplicate of that. – phils Jan 18 '17 at 20:45
  • @phils yea that's a good answer, thanks. So, it doesn't need to copy the keymap, but only set the parent. – Rorschach Jan 18 '17 at 22:11
  • If you copy a keymap then future changes to the original would not be reflected in the copy; so directly using the original as a parent is a more robust approach. – phils Jan 18 '17 at 22:58

0 Answers0