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.

3

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}")
  • Great, this works, though I'd do the set-keymap-parent inside of the defvar to keep everything together. – Tianxiang Xiong Feb 10 '17 at 6:11
  • Sure, that makes sense. – Tyler Feb 10 '17 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 '17 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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