help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: doubt about mode hooks


From: Emanuel Berg
Subject: Re: doubt about mode hooks
Date: Mon, 03 Jun 2013 22:14:28 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.4 (gnu/linux)

Luca Ferrari <fluca1978@infinito.it> writes:

> (add-hook 'c-mode-hook (lambda()
>                          (my-function-hook) )
>
> but then I come across a snippet that does something different:
>
> (setq my-personal-hook 'my-function-hook)
> (add-hook c-mode-hook (lambda ()
>                         (run-hooks 'my-personal-hook) ) t )
>
> so I was wondering what are the differences and which advantages
> should I get using the second.

If you have something that you wish to hook to several events (or
the same event, but in several modes), you can put that something
in a function, that will, in turn, add the hook. Where you
originally would have put that something, you can now (perhaps
easier) just add a reference to the function, and the material
will be added as a hook.

If that was difficult to follow, let me give you an example. For
almost all my typing, be it programming or not, I don't care for
tabs. So for a lot of modes, I like an untab-all invocation on
write. But, as there are exceptions to this rule (for example, GNU
makefiles which need tabs), I cannot make it global; it has to be
setup mode for mode. Thus:

(defun add-write-contents-hooks-hook ()
  (interactive)
  (add-hook
   'write-contents-hooks
   'untab-all
      nil  ; APPEND  unrelated, explicit default nil as optional
      t )) ; LOCAL   non-nil => make hook local

(add-hook 'emacs-lisp-mode-hook #'add-write-contents-hooks-hook)
(add-hook 'c-mode-common-hook   #'add-write-contents-hooks-hook)
(add-hook 'sh-mode-hook         #'add-write-contents-hooks-hook)
; ...

I agree hooks can be confusing. As a rule of thumb, don't rely on
them when it is not needed. Lots of stuff can be placed elsewhere,
so they won't slow down everything. If you can solve a problem by
placing stuff in a hook - do it! - but as your skills grow, always
be on the lookout for when the possibility arises to lighten the
burden on the hooks.

-- 
Emanuel Berg - programmer (hire me! CV below)
computer projects: http://user.it.uu.se/~embe8573
internet activity: http://home.student.uu.se/embe8573


reply via email to

[Prev in Thread] Current Thread [Next in Thread]