For example, let’s say I were to change backward-delete-char-untabify-method for prog-mode buffers. Naively, I’d write something like,

(add-hook 'prog-mode-hook (lambda ()
                       (setq-local backward-delete-char-untabify-method 'hungry)))

but the documentation recommends against using lambdas in add-hook calls (which makes sense). I can, of course, just make a named function instead of a lambda and pass that to add-hooks. But, rather than do that, is there any other option for setting variables automatically for modes besides a hook like this?

Also, as a bonus question, if I wanted to also do something like enable show-paren-mode for all prog-mode buffers, which of the following do you consider “better” (assume that this is not something that is likely to change frequently):

;; option 1
(defun my-prog-mode-settings ()
  (setq-local backward-delete-char-untabify-method 'hungry))

(add-hook 'prog-mode-hook #'my-prog-mode-settings)
(add-hook 'prog-mode-hook #'show-paren-mode)

;; option 2
(defun my-prog-mode-settings ()
  (setq-local backward-delete-char-untabify-method 'hungry)
  (show-paren-mode))

(add-hook 'prog-mode-hook #'my-prog-mode-settings)

Obviously, I realize that it’s not really important, but I feel like bike-shedding this morning.

  • JDRiverRunB
    link
    fedilink
    English
    arrow-up
    1
    ·
    10 months ago

    You can also use this approach:

    (add-hook 'text-mode-hook
              (defalias 'my/fancy-mode-setup
                (let (some-closure-var)
                  (lambda () ...))))
    

    Advantage is that there can be only one alias, and it’s added by name to the hook. So you can alter and re-run add-hook without duplication, and you can easily remove it by name. Best of all, you can create a closure (the let there) if you need that gives you “local storage in the function” that persists between runs (without cluttering the namespace with global variables).