Subject: bug#74448: 30.0.92; c-ts-mode outlines only work with GNU or emacs style

From: Filippo Argiolas <[email-masked]>
Date: Fri, 22 Nov 2024 07:01:30 +0100

Juri Linkov <[email-masked]> writes:

>> At the moment I am experimenting with this solution (DEFUN part omitted
>> for brevity) but it's probably missing some edge case I am not aware of:
>>
>> (defun c-ts-mode--outline-predicate (node)
>>   "Match outlines on lines with function names."
>>   (when-let* ((decl (treesit-node-child-by-field-name
>>                      (treesit-node-parent node) "declarator"))
>>               (node-pos (treesit-node-start node))
>>               (decl-pos (treesit-node-start decl))
>>               (eol (save-excursion (goto-char node-pos) (line-end-position))))
>>     (and (equal (treesit-node-type decl) "function_declarator")
>>          (<= node-pos decl-pos)
>>          (< decl-pos eol))))
>>
>> Idea is to match a function declarator in the same line as `node' no
>> matter what node is at bol.
>
> Thanks, I confirm your solution is better than the current state.
> Hope you could find a common denominator that covers all possible cases.

Seems to work with the code I tested. Guess it's still not perfect, if a
function declaration is splitted over multiple lines it will be folded
where the function name is and I think that's what we want.

A minor problem is with GNU style declarations type and storage class
specifier will go in to the previous subtree when you collapse
everything.

But it's probably good enough. As far as I can tell the way it works now
it folds from one outline to the next. The treesitter way would be to
fold up to where the toplevel node ends.

Maybe that's the job for a more specialized treesit folding package and
this is already good for outline-minor-mode.

By the way, the complete defun with Emacs source parsing restored is:

(defun c-ts-mode--outline-predicate (node)
  "Match outlines on lines with function names."
  (or (when-let* ((decl (treesit-node-child-by-field-name
                         (treesit-node-parent node) "declarator"))
                  (node-pos (treesit-node-start node))
                  (decl-pos (treesit-node-start decl))
                  (eol (save-excursion (goto-char node-pos) (line-end-position))))
        (and (equal (treesit-node-type decl) "function_declarator")
             (<= node-pos decl-pos)
             (< decl-pos eol)))
      ;; DEFUNs in Emacs sources.
      (and c-ts-mode-emacs-sources-support
           (c-ts-mode--emacs-defun-p node))))

Feel free to improve on this if you decide to install it, I never did
the copyright assignment but I think it's trivial enough to enter
without it.

Thanks!
Filippo