Re: Better c-ts-mode indentation when there are macros in the way
Yuan Fu <[email protected]> Fri, 24 Jul 2026 20:59:58 -0700
| Newsgroups | gmane.emacs.devel |
|---|---|
| Message-ID | <[email protected]> |
> On Jul 24, 2026, at 1:48 AM, Yuan Fu <[email protected]> wrote: > > > >> On Jul 18, 2026, at 1:24 AM, Eli Zaretskii <[email protected]> wrote: >> >>> Date: Sat, 04 Jul 2026 08:45:36 +0300 >>> From: Eli Zaretskii <[email protected]> >>> Cc: [email protected] >>> >>>> From: Björn Lindqvist <[email protected]> >>>> Date: Fri, 3 Jul 2026 18:26:27 +0200 >>>> >>>> Hello Emacs developers! >>>> >>>> Two years ago I posted about my woes getting c-ts-mode to indent >>>> C code the way I wanted in the presence of preprocessor macros: >>>> >>>> https://lists.gnu.org/archive/html/emacs-devel/2024-11/msg00806.html >>>> >>>> To summarize, there are two problems related to how tree-sitter parses >>>> preprocessor macros. The first is that #if and #else becomes part of >>>> the parse tree. So tree-sitter indentation rules like (parent-is >>>> "something") fails. The second problem is that preprocessor macros >>>> cause incorrect parse trees of unbraced block statements: >>>> >>>> if (true) >>>> #define M >>>> printf("ooo"); >>>> >>>> Neither the macro nor the printf becomes the child of the if >>>> statement. >>>> >>>> I solved these problems by creating two functions that walks the parse >>>> tree upwards to find the "real"/semantic parent of a node that I use like this: >>>> >>>> (my/c-parent-is "translation_unit") column-0 0) >>>> (my/real-c-parent-is-container my/real-c-parent-bol ,ofs) >>>> >>>> Implementation here: >>>> >>>> https://gist.github.com/bjourne/63ffea0c420bf84104c3f98ca1623ea6 >>>> >>>> My elisp is admittedly pretty bad, but it works, and is not as brittle >>>> as I thought it would be. Could something like this be added to >>>> cs-ts-mode or tree-sitter? >>> >>> Thanks. >>> >>> Theo and Yuan, any comments on that? >> >> Ping! > > As sorry, I meant to look at it. Let me wrap my head around the code first. But it sounds promising! I read through it and I like it! Especially since we’re limiting ourselves to just indentation and further just the parent-is rule, we only need to handle the case where the directive is the first line in the if body, and that makes the heuristic very simple. Very clever! I’ll incorporate this into c-ts-mode with some changes. BTW, since you’ve been using this for a while, do you see any edge cases that this doesn’t handle? You mentioned that it’s not as brittle as you imagined, but did you encounter any concrete cases where it didn’t work? Yuan