Subject: Re: bug#79363: 31.0.50; Font locking issue in go-ts-mode when tree-sitter grammar is automatically installed

From: Juri Linkov <[email-masked]>
Date: Tue, 02 Sep 2025 19:56:51 +0300

>> One idea is to turn defvar into defun that memoizes its return value.
>
> Do you mean something like this?

Exactly.

>   (defvar go-ts-mode--font-lock-settings nil
>     "Tree-sitter font-lock settings for `go-ts-mode'.")
>   
>   (defun go-ts-mode--font-lock-settings ()
>     "Return tree-sitter font-lock settings for `go-ts-mode'.
>   
>   Tree-sitter font-lock rules are evaluated the first time this function
>   is called.  Subsequent calls return the first evaluated value."
>     (or go-ts-mode--font-lock-settings
>         (setq go-ts-mode--font-lock-settings
>               (treesit-font-lock-rules
>                ...))))
>   
>   (define-derived-mode go-ts-mode prog-mode "Go"
>     ...
>     (when (treesit-ensure-installed 'go)
>       ...
>       (setq-local treesit-font-lock-settings (go-ts-mode--font-lock-settings))
>       ...))
>
> I tried and I can confirm it works fine.  I can work on a patch for all
> the affected ts modes if you want.

Thanks, this would be nice.

> BTW is this a common pattern?  If it is, does the Elisp core library
> provide something similar?  At the end of the day it is a sort of
> "lazy defvar", isn't it?

At the moment I don't see a better solution.  For example,
like the existing `with-eval-after-load' we could add
`with-eval-after-grammar-installed' with some hook called
when the grammar gets installed, e.g.:

  (defun go-ts-mode--font-lock-settings ()
    (with-eval-after-grammar-installed 'go
      (setq go-ts-mode--font-lock-settings
            (treesit-font-lock-rules
             ...))))

But even with this additional complexity its usage
is not simpler than you suggested above.