Subject: Re: bug#56637: 28.1.90; [FR] Allow a way around font-lock-mode being unconditionally disabled in " *hidden*" buffers

From: Stefan Monnier <[email-masked]>
Date: Tue, 19 Jul 2022 13:01:38 -0400

>> FWIW, I do think it would be good to remove the rule that font-lock is
>> never enabled in temp buffers.
> I don't.

I think we agree :-)

More seriously, I didn't mean to remove it willy-nilly, but that it's
a desirable goal and the question is how to get there.

We could start by adding a new variable
`font-lock-allow-in-temporary-buffer`, which packages could set
buffer-locally in those rare temp buffers where they do want to enable
font-lock, as in the untested patch below.

Of course, the problem in `font-lock-ensure` is orthogonal to this.

        Stefan

diff --git a/lisp/font-core.el b/lisp/font-core.el
index f92d1e38306..f74d1d854a0 100644
--- a/lisp/font-core.el
+++ b/lisp/font-core.el
@@ -78,6 +78,13 @@ font-lock-function
 ;; The mode for which font-lock was initialized, or nil if none.
 (defvar font-lock-major-mode)
 
+(defvar-local font-lock-allow-in-temporary-buffer nil
+  "If non-nil, override the temp-buffer limitation.
+Normally `font-lock-mode' cannot be enabled in buffers never intended
+to be displayed (i.e. temp buffers and batch mode).
+Set this variable to non-nil in those rare buffers where `font-lock-mode'
+is needed even though they'll never be displayed.")
+
 (define-minor-mode font-lock-mode
   "Toggle syntax highlighting in this buffer (Font Lock mode).
 
@@ -131,13 +138,14 @@ font-lock-mode
   :after-hook (font-lock-initial-fontify)
   ;; Don't turn on Font Lock mode if we don't have a display (we're running a
   ;; batch job) or if the buffer is invisible (the name starts with a space).
-  (when (or noninteractive (eq (aref (buffer-name) 0) ?\s))
+  (when (and (or noninteractive (eq (aref (buffer-name) 0) ?\s))
+             (not font-lock-allow-in-temporary-buffers))
     (setq font-lock-mode nil))
   (funcall font-lock-function font-lock-mode)
   ;; Arrange to unfontify this buffer if we change major mode later.
   (if font-lock-mode
-      (add-hook 'change-major-mode-hook 'font-lock-change-mode nil t)
-    (remove-hook 'change-major-mode-hook 'font-lock-change-mode t)))
+      (add-hook 'change-major-mode-hook #'font-lock-change-mode nil t)
+    (remove-hook 'change-major-mode-hook #'font-lock-change-mode t)))
 
 ;; Get rid of fontification for the old major mode.
 ;; We do this when changing major modes.