emacs: mode hook is bypassed when mode is switched by hand

86 Views Asked by At

In my .emacs there is the following mode hooks:

(defun my-html-mode-hook ()
  (interactive)
  (setq tab-width 4
        ;; this will make sure TABs are used instead of spaces
        indent-tabs-mode t)
  )

(defun my-javascript-mode-hook ()
  (interactive)
  (setq tab-width 4
        ;; this will make sure TABs are used instead of spaces
        indent-tabs-mode t)
  )


(add-hook 'javascript-mode-hook 'my-javascript-mode-hook)
(add-hook 'html-mode-hook 'my-html-mode-hook)

Now when I am opening a .html, it works as expected, same for opening .js.

However, when opening .html and then switching to JavaScript by M-x javascript-mode by hand, my-javascript-mode-hook is not run (at least tab width switches to 8). How to make that hook run when I switch the mode manually?

2

There are 2 best solutions below

0
emacs drives me nuts On

There appears to be a dreaded ambiguity in naming, namely both javascript-mode-hook and js-mode-hook are recognized and run on startup when a JavaScript file is opened.

However, when switching to JavaScript by hand, only js-mode-hook is run. Both js-mode and javascript-mode mode trigger JavaScript mode (at least they are displayed as (JavaScript) in the status line), so someone got tired of typing the "avacript" letters and kicked them out of "javascript" but forgot to clean up some mess...

0
phils On

There is no javascript-mode-hook, I'm afraid. Certainly not by default.

javascript-mode is an alias for js-mode, meaning that only js-mode-hook is defined. However, variable aliases are also a thing -- I suggest you M-x report-emacs-bug and ask whether javascript-mode-hook might be defined as a variable alias for js-mode-hook. So long as that defvaralias was autoloaded (along with the mode's alias, and hence before you've used it), I believe it would work as desired.

As such, and as I expected, I am unable to reproduce/confirm your assertion that javascript-mode-hook "works as expected" in the case of opening a .js file. Your code does not behave that way in either Emacs 26.3 or 27.0.90.