Subject: Re: bug#65470: 29.1.50; js-ts-mode: regex pattern can cause incorrect parenthesis matching

From: Augustin Chéneau (BTuin) <[email-masked]>
Date: Thu, 24 Aug 2023 21:31:33 +0200

I have created a patch heavily inspired from ruby-ts-mode.

It fixes the trivial examples and it works as expected in a more complex 
file.
I'm not sure if the commit message is formatted properly.

From d7bb7a77a57026f385c4137a25199eb2a2c15768 Mon Sep 17 00:00:00 2001
From: Augustin Chéneau <[email-masked]>
Date: Thu, 24 Aug 2023 21:00:47 +0200
Subject: [PATCH] Apply syntax properties to regex delimiters in js-ts-mode

Add a property to regex slashes to avoid incorrect parenthesis
pairing by using `syntax-propertize-function` (Bug#65470)
* lisp/progmodes/js.el: add a new function to apply syntax properties
---
 lisp/progmodes/js.el | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/lisp/progmodes/js.el b/lisp/progmodes/js.el
index 9d2990e7bc9..efdddfeadf4 100644
--- a/lisp/progmodes/js.el
+++ b/lisp/progmodes/js.el
@@ -3711,6 +3711,23 @@ js--treesit-valid-imenu-entry
     ("lexical_declaration" (treesit-node-top-level node))
     (_ t)))
 
+(defvar js-ts--regex-query
+  (when (treesit-available-p)
+    (treesit-query-compile 'javascript
+                           '(((regex "/" @regex_slash))))))
+
+(defun js-ts-mode--syntax-propertize (beg end)
+  "Apply syntax properties to special characters between BEG and END.
+
+Apply syntax properties to regex delimiters (slashes)."
+  (let ((captures (treesit-query-capture 'javascript js-ts--regex-query beg end)))
+    (pcase-dolist (`(,name . ,node) captures)
+      (pcase-exhaustive name
+	('regex_slash
+	 (put-text-property (treesit-node-start node) (1+ (treesit-node-start node))
+			    'syntax-table
+			    (string-to-syntax "\"/")))))))
+
 ;;; Main Function
 
 ;;;###autoload
@@ -3850,6 +3867,9 @@ js-ts-mode
                   ( assignment constant escape-sequence jsx number
                     pattern string-interpolation)
                   ( bracket delimiter function operator property)))
+    ;; Syntax table
+    (setq-local syntax-propertize-function
+                #'js-ts-mode--syntax-propertize)
     ;; Imenu
     (setq-local treesit-simple-imenu-settings
                 `(("Function" "\\`function_declaration\\'" nil nil)
-- 
2.42.0