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.

  • astoff1@alien.topB
    link
    fedilink
    English
    arrow-up
    1
    ·
    11 months ago

    When it comes to personal configuration, I see no good reason not to use lambdas in this case. I also use them a lot when binding keys to simple commands which I don’t want to name.

    Also: option 1.

    • 7890yuiop@alien.topB
      link
      fedilink
      English
      arrow-up
      1
      ·
      11 months ago
      • They used to be hard to remove. As mentioned, M-x remove-hook has alleviated that to an extent.
      • They are still harder to update because you need to remember to remove the old one when adding the replacement. I’ve seen any number of cases where people were inadvertently adding lots of slightly different versions of their function to a hook variable, and wondering why they were still having problems.
      • They are very unhelpful when you inspect the hook variable. Rather than seeing a function name (from which you could jump to the nicely-formatted function definition), you see at best the lisp code all jammed into a single line, and at worst a heap of unreadable byte-code.

      Use named functions. It’s just better.