Subject: bug#61208: 29.0.60; treesit-beginning/end-of-defun problem with macros in c-ts-mode

From: Yuan Fu <[email-masked]>
Date: Wed, 1 Feb 2023 18:32:26 -0800

> On Feb 1, 2023, at 4:49 AM, Eli Zaretskii <[email-masked]> wrote:
> 
>> Cc: [email-masked]
>> Date: Wed, 01 Feb 2023 14:33:24 +0800
>> From:  Yang Yingchao via "Bug reports for GNU Emacs,
>> the Swiss army knife of text editors" <[email-masked]>
>> 
>> 
>> #define SWITCH()
>> #define CASE(name) case name:
>> 
>> void func(int i)        // LINE_E
>> {
>>    SWITCH(i)           // LINE_D
>>    {
>>        CASE(A)         // LINE_C
>>        {
>>            ;
>>        }
>>        CASE(B)         // LINE_B
>>        {
>>            ;           // LINE_A
>>        }
>>    }
>> }
>> 
>> When cursor is at LINE_A, and stoke `C-M-a`, cursor will go to LINE_B;
>> then `C-M-a` again, cursor goes to LINE_C, then `C-M-a` again, LINE_D,
>> and `C-M-a` again, finally to LINE_E...
> 
> Set treesit-defun-tactic to 'top-level, and your problem is solved.
> 
> Yuan, Theo: do we want to have that set by default in ts-c-mode?  C
> doesn't have nested functions, so it should be a better default, what
> with all the cpp madness that the C grammar doesn't grok.
> 
> Maybe also in C++ and Java -- AFAIU they don't have nested functions
> either.

Treesit-defun-tactic being ’nested isn’t the problem here, at least not the direct cause of the problem. c-ts-mode doesn’t consider switch cases or if-else statements as defuns. It only considers function, struct, enum, union, as defun. So in a preprocessed C source file, C-M-a will move point to the beginning of the function, line E. It does not in this particular file because tree-sitter is thrown off by the SWITCH() and CASE() macro: it can’t tell what they are and parses them as function definitions.

I don’t object setting treesit-defun-tactic to ’top-level in c-ts-mode, though. It can hide problems like this. Just be aware that it merely hides the problem.

C++ and Java has classes, and when point is in a class, I think people expect to move to the prev/next method rather than the beginning/end of the class. So nested is still a better default IMO.

Yuan