From 63f8a838eccf201d6290d0dc8f83881f41785afb Mon Sep 17 00:00:00 2001 From: Yuan Fu Date: Tue, 15 Nov 2022 02:30:50 -0800 Subject: [PATCH] Make tree-sitter fontification automatically update Now nodes that are affected and changed during re-parse will be correctly refontified. Nodes can change even if it corresponding text wasn't edited: additional text can complete the parse tree and resolve error nodes, for example. * lisp/progmodes/python.el (python-mode): Create Python parser before calling treesit-major-mode-setup. * lisp/treesit.el (treesit--font-lock-notifier): New function. (treesit-major-mode-setup): Register fontifier with every existing parser. --- lisp/progmodes/python.el | 1 + lisp/treesit.el | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lisp/progmodes/python.el b/lisp/progmodes/python.el index 7919484e096..ad4665eb19c 100644 --- a/lisp/progmodes/python.el +++ b/lisp/progmodes/python.el @@ -6548,6 +6548,7 @@ Add import for undefined name `%s' (empty to skip): " (cond ;; Tree-sitter. ((treesit-ready-p 'python-mode 'python) + (treesit-parser-create 'python) (setq-local treesit-font-lock-feature-list '(( comment string function-name class-name) ( keyword builtin constant type) diff --git a/lisp/treesit.el b/lisp/treesit.el index 31a31dda417..ef43391080c 100644 --- a/lisp/treesit.el +++ b/lisp/treesit.el @@ -838,6 +838,14 @@ If LOUDLY is non-nil, display some debugging information." face (treesit-node-type node))))))))))) `(jit-lock-bounds ,start . ,end)) +(defun treesit--font-lock-notifier (ranges parser) + "Ensures updated parts of the parse-tree is refontified. +RANGES is a list of (BEG . END) ranges, PARSER is the tree-sitter +parser notifying of the change." + (with-current-buffer (treesit-parser-buffer parser) + (dolist (range ranges) + (put-text-property (car range) (cdr range) 'fontified nil)))) + ;;; Indent (define-error 'treesit-indent-error @@ -1527,7 +1535,10 @@ enable `font-lock-mode'. If `treesit-simple-indent-rules' is non-nil, setup indentation. If `treesit-defun-type-regexp' is non-nil, setup -`beginning/end-of-defun' functions." +`beginning/end-of-defun' functions. + +Make sure necessary parsers are created for the current buffer +before calling this function." ;; Font-lock. (when treesit-font-lock-settings ;; `font-lock-mode' wouldn't setup properly if @@ -1537,7 +1548,10 @@ If `treesit-defun-type-regexp' is non-nil, setup (font-lock-fontify-syntactically-function . treesit-font-lock-fontify-region))) (font-lock-mode 1) - (treesit-font-lock-recompute-features)) + (treesit-font-lock-recompute-features) + (dolist (parser (treesit-parser-list)) + (treesit-parser-add-notifier + parser #'treesit--font-lock-notifier))) ;; Indent. (when treesit-simple-indent-rules (setq-local treesit-simple-indent-rules -- 2.39.2