Subject: [PATCH] Fontify C++ function definitions in c++-ts-mode

From: Daniel Martín <[email-masked]>
Date: Tue, 03 Jan 2023 23:15:41 +0100

Tags: patch

Given the following valid C++ code:

void Foo::bar() {

}

c++-ts-mode should fontify bar with the font-lock-function-name-face
face.  The attached patch adds support for fontifying function
declarations whose identifier is "buried" inside qualified_identifier
nodes.

I've checked that the patch also fontifies bar in

void Foo::Bar::bar() {

}

but fontifies bar with font-lock-variable-name-face face in the
following cases:

Foo::Bar::Bar2 bar;
Foo::Bar bar;

I don't check for C++ mode in the code, as I think the impact of this
new check should be negligible for C code, but I'm open to feedback.

Thanks.

>From 6e687edc303ba5dba5f58479ad076c4ab9b610f6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Mart=C3=ADn?= <[email-masked]>
Date: Tue, 3 Jan 2023 22:08:13 +0100
Subject: [PATCH] Fontify C++ function definitions in c-ts-mode

* lisp/progmodes/c-ts-mode.el (c-ts-mode--declarator-identifier):
Teach the code how to extract the declarator of a node of type
"qualified_identifier".
(c-ts-mode--fontify-declarator): Consider the case where the
identifier in a function declarator is buried inside
"qualifier_identifier" nodes.
---
 lisp/progmodes/c-ts-mode.el | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/lisp/progmodes/c-ts-mode.el b/lisp/progmodes/c-ts-mode.el
index ba38845a084..30a14ecdfae 100644
--- a/lisp/progmodes/c-ts-mode.el
+++ b/lisp/progmodes/c-ts-mode.el
@@ -430,6 +430,9 @@ c-ts-mode--declarator-identifier
     ((or "function_declarator" "array_declarator" "init_declarator")
      (c-ts-mode--declarator-identifier
       (treesit-node-child-by-field-name node "declarator")))
+    ("qualified_identifier"
+     (c-ts-mode--declarator-identifier
+      (treesit-node-child-by-field-name node "name")))
     ;; Terminal case.
     ((or "identifier" "field_identifier")
      node)))
@@ -439,7 +442,14 @@ c-ts-mode--fontify-declarator
 For NODE, OVERRIDE, START, END, and ARGS, see
 `treesit-font-lock-rules'."
   (let* ((identifier (c-ts-mode--declarator-identifier node))
-         (face (pcase (treesit-node-type (treesit-node-parent identifier))
+         (qualified-root
+          (treesit-parent-while (treesit-node-parent identifier)
+                                (lambda (node)
+                                  (equal (treesit-node-type node)
+                                         "qualified_identifier"))))
+         (face (pcase (treesit-node-type (treesit-node-parent
+                                          (or qualified-root
+                                              identifier)))
                  ("function_declarator" 'font-lock-function-name-face)
                  (_ 'font-lock-variable-name-face))))
     (treesit-fontify-with-override
-- 
2.34.1