1

So I've got this file called hooks.el in my emacs.d with this kind of content:

(add-hook 'term-mode-hook ...)
(add-hook 'term-exec-mode-hook ...)
(add-hook 'python-mode-hook ...)
(add-hook 'ido-setup-hook ...)
(add-hook 'makefile-mode-hook ...)
(add-hook 'c-mode-common-hook ...)
(add-hook 'c-mode-hook ...)
(add-hook 'c++-mode-hook ...)
(add-hook 'dired-mode-hook
      (lambda()
        (define-key dired-mode-map "h" 'dired-previous-line)
        (define-key dired-mode-map "j" 'ido-find-file)
            ;; ...
            ))

I was just wondering if I'm doing something weird here or is this indeed the idiomatic way to assign shortcuts based on mode?

I mean here adding hooks instead of plainly writing:

(define-key dired-mode-map "h" 'dired-previous-line)

Of course, this won't work unless dired is loaded and dired-mode-map is defined, hence the hook. And it's probably not the best thing to just load all the modes, even if I'm not using them always, just to define the custom shortcuts. But on the other hand, the hook is being run for every new buffer open - and all these shortcuts are being redefined over and over, instead of just once.

What's your take one the matter? I'm sure there's something more optimal that I could switch to.

In the meantime, I can show off the bookmarklet for my hooks.el:

(defun goto-hook-file ()
  "Opens hooks.el at point specific to current `major-mode'"
  (interactive)
  (let ((str-mode-hook (format "%s-hook" major-mode)))
    (find-file (concat emacs.d "hooks.el"))
    (goto-char (point-min))
    (search-forward str-mode-hook nil t)))
abo-abo
  • 20,038
  • 3
  • 50
  • 71
  • You should probably change the question title; at the moment it's pretty meaningless. Here's a very similar (if not quite duplicate) Q&A: http://stackoverflow.com/questions/9818307/emacs-mode-specific-custom-key-bindings-local-set-key-vs-define-key. – phils Jul 10 '13 at 21:36
  • Wouldn't say that it's entirely duplicate. I couldn't find it before I posted. And now my question has a link to the real deal:) – abo-abo Jul 11 '13 at 05:38

1 Answers1

4

You can use eval-after-load:

(eval-after-load 'dired
  '(progn
     (define-key dired-mode-map "h" 'dired-previous-line)
     (define-key dired-mode-map "j" 'ido-find-file)))

That way, the keys are only defined once.

Sean
  • 29,130
  • 4
  • 80
  • 105