Subject: Re: bug#62204: 30.0.50; Feature Request: treesit-major-mode-hook

From: Eli Zaretskii <[email-masked]>
Date: Thu, 16 Mar 2023 08:38:34 +0200

> From: Aleksandar Dimitrov <[email-masked]>
> Cc: [email-masked]
> Date: Thu, 16 Mar 2023 01:35:17 +0100
> 
> I'd like to be able to do something like this:
> 
> (defun my-setup ()
>   "Code that depends on the presence of TS")
> (add-hook 'treesit-major-mode-hook 'my-setup)
> 
> If I understand you correctly,  I could probably do something like this:
> 
> (defmacro add-ts-mode-hook (f)
>   "Add mode hook that only executes in ts modes"
>   `(add-hook 'prog-mode-hook
>             (lambda ()
>               (when (treesit-language-at (point))
>                 (,f)))))

Something like that.  Basically, any function that wants to do
something that depends on tree-sitter being available for the major
mode should make such a test to determine whether tree-sitter support
is available.

> I'd say there's bound to be more people who would like to configure a
> certain behaviour whenever treesit is available, regardless of major
> mode. A macro like the above could be a possible solution, but it
> doesn't feel terribly ergonomic.

The above code doesn't have to run from a mode hook, it could be done
directly where the "certain behavior" is implemented, as the condition
for invoking that certain behavior.  And if running the test each time
is too expensive for some reason, the test could be optimized by
performing it just once for each buffer where it runs, and saving the
result in some buffer-local variable.

If the above is for some reason unworkable or otherwise problematic,
please tell why.

> > A hooks sounds too blunt and ad-hoc for your purposes, AFAIU.
> 
> The reason I want to execute my function in a hook is that it sets
> buffer local variables, and configures buffer-local behaviour, perhaps
> even keybindings. I was under the impression that hooks are the correct
> place to do this.

They are, but they are not the only such place.  Many features in
Emacs use buffer-local variables and keybindings without a special
hook.

Please also keep in mind that proliferation of general-purpose hooks
is not without disadvantages.  For starters, a hook disconnects the
cause from the effect, and makes it harder to track the control flow
and thus harder to understand how a given Lisp program works.