I want to hook {whitespace a开发者_运维百科nd yas/minor-mode} minor modes to some major modes. Of course that could be done, manually, but I want a loop. So I tried to write it:
(progn
(setq modes-to-be-hooked '(lisp-mode-hook rst-mode-hook python-mode-hook emacs-lisp-mode-hook text-mode-hook tcl-mode-hook c-mode-hook fortran-mode-hook))
(while modes-to-be-hooked
(setq my-hooks '( yas/minor-mode whitespace-mode ))
(while my-hooks
(add-hook '(pop modes-to-be-hooked) '(pop my-hooks)))
)
)
The problem with this loop is that the last element of list is "nil" and (add-hook 'nil 'nil) gives an error. Then I tried to escape nils with if, but it doesn't work:
(progn
(setq mylist '(a b c))
(while mylist
(progn
(setq temp (pop mylist))
(if temp (message "%s" temp) (message "It's nil!") )
(sleep-for 1)
)
)
)
prints nil :(
Well I can see a couple of problems with your code. Firstly, you are popping from your major mode list every time you pop from your minor mode list. Secondly, you are quoting your (pop)
calls, which means you are not passing the values you want into (add-hook)
.
A while loop does not execute its body when the loop value is nil, so your second block of code doesn't produce nil
via your (message)
because it doesn't get that far. nil is simply the final value produced in that (progn)
, being the eventual return value of the while loop when it encounters nil.
You might want to check out the interactive debugging support in Emacs so that you can figure out what is actually happening if your code isn't behaving the way you expected. See:
M-: (info "(elisp) debugging")
RET
However, I would suggest using lhui's solution rather than fixing what you have.
For an alternative syntax, I use this approach:
(defun my-coding-config ()
(whitespace-mode 1)
(yas/minor-mode 1))
(mapc
(lambda (language-mode-hook)
(add-hook language-mode-hook 'my-coding-config))
'(lisp-mode-hook
rst-mode-hook
python-mode-hook
emacs-lisp-mode-hook
text-mode-hook
tcl-mode-hook
c-mode-hook
fortran-mode-hook))
Defining a named function like my-coding-config
simplifies things if you decide to include some new functionality later (such as including another minor mode) as you can make the change take immediate effect simply by re-evaluating that one function, rather than removing/adding items to all those hook variables.
use this:
(dolist (hook (list lisp-mode-hook rst-mode-hook python-mode-hook emacs-lisp-mode-hook text-mode-hook tcl-mode-hook c-mode-hook fortran-mode-hook)) (add-hook hook (lambda () (whitespace-mode 1) (yas/minor-mode 1))))
精彩评论