Improve tree-sitter's prev-sibling indent anchor

Now it handles the case where NODE is nil when indenting an empty
line: it tries to get the previous sibling nonetheless.

* lisp/progmodes/c-ts-mode.el (c-ts-mode--anchor-prev-sibling):
* lisp/treesit.el (treesit-simple-indent-presets): Add an or form to
handle more cases.
This commit is contained in:
Yuan Fu 2023-03-01 13:55:53 -08:00
parent db50545e3e
commit 6b2720778d
No known key found for this signature in database
GPG key ID: 56E19BC57664A442
2 changed files with 19 additions and 5 deletions

View file

@ -257,7 +257,7 @@ is actually the parent of point at the moment of indentation."
0
c-ts-mode-indent-offset)))
(defun c-ts-mode--anchor-prev-sibling (node &rest _)
(defun c-ts-mode--anchor-prev-sibling (node parent bol &rest _)
"Return the start of the previous named sibling of NODE.
This anchor handles the special case where the previous sibling
@ -273,8 +273,14 @@ The anchor of \"int y = 2;\" should be \"int x = 1;\" rather than
the labeled_statement.
Return nil if a) there is no prev-sibling, or 2) prev-sibling
doesn't have a child."
(when-let ((prev-sibling (treesit-node-prev-sibling node t)))
doesn't have a child.
PARENT and BOL are like other anchor functions."
(when-let ((prev-sibling
(or (treesit-node-prev-sibling node t)
(treesit-node-prev-sibling
(treesit-node-first-child-for-pos parent bol) t)
(treesit-node-child parent -1 t))))
(while (and prev-sibling
(equal "labeled_statement"
(treesit-node-type prev-sibling)))

View file

@ -1237,9 +1237,17 @@ See `treesit-simple-indent-presets'.")
(line-beginning-position))
(throw 'term (point)))
(setq parent (treesit-node-parent parent)))))))
(cons 'prev-sibling (lambda (node &rest _)
(cons 'prev-sibling (lambda (node parent bol &rest _)
(treesit-node-start
(treesit-node-prev-sibling node))))
(or (treesit-node-prev-sibling node t)
;; If node is nil (indenting empty
;; line), we still try to guess the
;; previous sibling.
(treesit-node-prev-sibling
(treesit-node-first-child-for-pos
parent bol)
t)
(treesit-node-child parent -1 t)))))
(cons 'no-indent (lambda (_n _p bol &rest _) bol))
(cons 'prev-line (lambda (_n _p bol &rest _)
(save-excursion