Skip to content

Instantly share code, notes, and snippets.

@sogaiu
Last active April 7, 2026 15:01
Show Gist options
  • Select an option

  • Save sogaiu/d89f9193c0f91cff51a723533065bc46 to your computer and use it in GitHub Desktop.

Select an option

Save sogaiu/d89f9193c0f91cff51a723533065bc46 to your computer and use it in GitHub Desktop.
"some option to infer the closing parentheses before it gets passed to whatever tree representation this mode is operating on"
;; from: https://github.com/clojure-emacs/clojure-ts-mode/issues/134#issuecomment-4178337890
;; by: https://github.com/sstraust
;; the thought is to temporarily insert the parens just before sending to
;; treesitter, and then remove them so they don't impact the user's working
;; buffer
(defun treesitter-parens--compute-closing-chars ()
(save-excursion
(save-restriction
(widen)
(let* ((curr-expr (parse-partial-sexp (point-min) (point-max)))
(unclosed-expr-positions (nth 9 curr-expr))
(closing-chars '()))
(dolist (pos unclosed-expr-positions)
(let ((closing-char (matching-paren (char-after pos))))
(when closing-char
(push closing-char closing-chars))))
(when (nth 3 curr-expr)
(push (nth 3 curr-expr) closing-chars))
(apply #'string closing-chars)))))
(defun treesitter-parens--advice (orig-fn &rest args)
(let ((closing-chars (treesitter-parens--compute-closing-chars))
(buffer-undo-list t)
(before-change-functions nil)
(after-change-functions nil)
(was-modified (buffer-modified-p)))
(insert closing-chars)
(unwind-protect
(apply orig-fn args)
(unless (string-empty-p closing-chars)
(search-backward closing-chars)
(delete-region (match-end 0) (- (match-end 0) (length closing-chars))))
(unless was-modified (restore-buffer-modified-p nil)))))
(advice-add 'treesit-font-lock-fontify-region
:around #'treesitter-parens--advice)
(advice-add 'treesit-indent
:around #'treesitter-parens--advice)
(provide 'clojure-ts-mode-extras)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment