3

It seems that when using define-derived-mode, the new mode's keymap is merged with that of the parent mode. Is there a way to avoid this? That is, to inherit font-lock, etc. from the parent mode, but have a completely new keymap.

E.g.

(defvar foo-mode-map
  (let ((map (copy-keymap special-mode-map)))
    (define-key map (kbd "n") #'next-line)
    (define-key map (kbd "p") #'previous-line)
    map)
  "Keymap for foo-mode.")

(define-derived-mode foo-mode java-mode "Foo"
  "Major mode derived from `java-mode'.

\\{foo-mode-map}")

I'd like foo-mode to use foo-mode-map without any key sequences from java-mode-map.

1 Answer 1

4

From the manual (elisp) Derived Modes, define-derived-mode defines keymaps using the following rules:

The new mode has its own sparse keymap, named ‘VARIANT-map’. ‘define-derived-mode’ makes the parent mode’s keymap the parent of the new map, unless ‘VARIANT-map’ is already set and already has a parent.

You've used copy-keymap to create your keymap, and this doesn't set a parent keymap. If you do that explicitly, your new keymap won't inherit from java-mode:

(defvar foo-mode-map
  (let ((map (copy-keymap special-mode-map)))
    (define-key map (kbd "n") #'next-line)
    (define-key map (kbd "p") #'previous-line)
     ;; Set parent map for foo-mode-map:
    (set-keymap-parent map special-mode-map)
     map)
  "Keymap for foo-mode.")

(define-derived-mode foo-mode java-mode "Foo"
  "Major mode derived from `java-mode'.

\\{foo-mode-map}")
4
  • Great, this works, though I'd do the set-keymap-parent inside of the defvar to keep everything together. Feb 10, 2017 at 6:11
  • Sure, that makes sense.
    – Tyler
    Feb 10, 2017 at 14:10
  • 2
    Don't use copy-keymap (for the same reason copy&paste of code is a bad idea). Instead do: (let ((map (make-sparse-keymap))) (set-keymap-parent map special-mode-map) ...).
    – Stefan
    Feb 11, 2017 at 23:41
  • Is there a way to derive all the keys from major mode and not define a particular key from major in the minor mode? Fall back to, what is defined by users initially globally?
    – noorul
    Jun 14, 2021 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.