Subject: Re: bug#77256: Treesit language-at-point

From: Yuan Fu <[email-masked]>
Date: Sat, 5 Apr 2025 21:51:29 -0700

> On Apr 5, 2025, at 11:35 AM, Juri Linkov <[email-masked]> wrote:
> 
>> Unfortunately, I discovered that it causes treesit-node-outdated errors.
>> 
>> This is because overlays are updated by 'pre-redisplay-functions'
>> later than outline-minor-mode uses them by 'after-change-functions',
>> since 'after-change-functions' runs before 'pre-redisplay-functions'.
> 
> This fixes the problem:
> 
>   (defun outline--fix-buttons-after-change (beg end _len)
>  +  (when (fboundp 'treesit-update-ranges)
>  +    (treesit-update-ranges beg end))
>     ;; Handle whole lines
>     (save-excursion (goto-char beg) (setq beg (pos-bol)))
>     (save-excursion (goto-char end) (setq end (pos-eol)))

Using treesit-update-ranges is the right approach. But is there no better place to put it? I assume there should be a function that involves tree-sitter, in front of which you can put this call.

> But can we do better?  I see that 'treesit-major-mode-setup'
> adds the notifier
> 
>      (treesit-parser-add-notifier
>       treesit-primary-parser #'treesit--font-lock-mark-ranges-to-fontify)
> 
> to 'after_change_functions'.  But why the treesit
> 'after_change_functions' notifier is called after the
> 'after-change-functions' hook?  Can we change their order?

Because we parse lazily. And I should’ve called them after-parse functions in the docstring (good thing I named them notifiers, not after-change-functions)—they get called after the parser re-parses, but the parser doesn’t have to re-parse immediately after a buffer change. It only re-parses when some Lisp asks for a node from the parse tree.

In practice, that usually happens in pre-redisplay-function where we set ranges for embedded parsers, which causes the primary parser to re-parse and return a root node for querying. As a (intended) side-effect, the notifiers get called and mark relevant regions to be re-fontified.

Yuan