Subject: bug#59662: 29.0.50; [PATCH] Add treesit--indent-defun

From: Theodor Thornhill <[email-masked]>
Date: Mon, 28 Nov 2022 20:32:01 +0100

Hi Eli and Yuan!

I've added a function to treesit.el, for use in
treesit-major-mode-setup.  Because the treesit-defun-type-regexp gives
us "defuns" for free, we can set fill-paragraph-function to this new
function, thus enabling quick formatting, and some sensible default for
fill-paragraph.  It aims to mirror c-indent-defun.

I think this is a nice way to get this functionality for free, but I'm
not 100% whether this is considered ok or not.

An alternative could be to add a 'treesit-mode-map' where we can
auto-enable such constructs.

Feel free to apply if it looks ok.

Theo

>From aed3f136d530c0eaa83c385cac7388c853b4f99a Mon Sep 17 00:00:00 2001
From: Theodor Thornhill <[email-masked]>
Date: Mon, 28 Nov 2022 20:19:20 +0100
Subject: [PATCH] Add treesit--indent-defun

We can piggyback on the already existing 'treesit-defun-type-regexp'
to decide a scope to reindent/reformat.  By setting
fill-paragraph-function major modes that implement
'treesit-defun-type-regexp' will get this functionality for free, by
default bound to M-q.

* lisp/treesit.el (treesit--indent-defun): New function.
(treesit-major-mode-setup): Enable this functionality when prereqs are
fulfilled.
---
 lisp/treesit.el | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)

diff --git a/lisp/treesit.el b/lisp/treesit.el
index 8f092f475d..685c59aedb 100644
--- a/lisp/treesit.el
+++ b/lisp/treesit.el
@@ -1451,6 +1451,21 @@ treesit-simple-indent
                         (message "No matched rule"))
                       (cons nil nil))))))
 
+(defun treesit--indent-defun (&optional _arg)
+  "Indent the current defun.
+
+Uses `treesit-defun-type-regexp' to determine which nodes to
+reindent."
+  (interactive)
+  (when-let ((defun-node
+              (save-excursion
+                (treesit-search-forward-goto
+                 (treesit-node-at (point))
+                 treesit-defun-type-regexp t t))))
+    (treesit-indent-region
+     (treesit-node-start defun-node)
+     (treesit-node-end defun-node))))
+
 (defun treesit-check-indent (mode)
   "Check current buffer's indentation against a major mode MODE.
 
@@ -1698,7 +1713,10 @@ treesit-major-mode-setup
   ;; Navigation.
   (when treesit-defun-type-regexp
     (setq-local beginning-of-defun-function #'treesit-beginning-of-defun)
-    (setq-local end-of-defun-function #'treesit-end-of-defun)))
+    (setq-local end-of-defun-function #'treesit-end-of-defun))
+  ;; Filling
+  (when (and treesit-defun-type-regexp treesit-simple-indent-rules)
+    (setq-local fill-paragraph-function #'treesit--indent-defun)))
 
 ;;; Debugging
 
-- 
2.34.1