From 745f9b6720d099c714ce92f8f82f43f66711df4a Mon Sep 17 00:00:00 2001
From: shipmints <shipmints@gmail.com>
Date: Fri, 17 Jan 2025 19:32:17 -0500
Subject: [PATCH] Add predicate function org-src-is-fontify-buffer-p

This can be used in a prog-mode hook to avoid resource-intensive
features such as eglot inside a fontification buffer. A short example
can be found in the function's docstring and in the corresponding NEWS
entry.
---
 etc/ORG-NEWS    |  6 ++++++
 lisp/org-src.el | 20 ++++++++++++++++++++
 2 files changed, 26 insertions(+)

diff --git a/etc/ORG-NEWS b/etc/ORG-NEWS
index adc48f304..0911c3bc9 100644
--- a/etc/ORG-NEWS
+++ b/etc/ORG-NEWS
@@ -200,6 +200,12 @@ take the date as an argument, and generate a list of pairs for
 ~org-datetree-find-create-hierarchy~.  This allows for creating new
 types of datetrees (e.g. for lunar calendars, academic calendars,
 retail 4-4-5 calendars, etc).
+*** Predicate test for fontify buffer
+
+The predicate function ~org-src-is-fontify-buffer-p~ can be used in a
+`prog-mode' hook to avoid resource-intensive features such as `eglot'
+inside a fontification buffer. A short example can be found in the
+function's docstring.
 
 ** New and changed options
 
diff --git a/lisp/org-src.el b/lisp/org-src.el
index 74343bde1..6459fb935 100644
--- a/lisp/org-src.el
+++ b/lisp/org-src.el
@@ -660,6 +660,25 @@ Leave point in edit buffer."
 
 ;;; Fontification of source blocks
 
+(defvar-local org-src--is-fontify-buffer nil)
+(put 'org-src--is-fontify-buffer 'permanent-local t) ; needs to survive major-mode housecleaning
+
+;;;###autoload
+(defun org-src-is-fontify-buffer-p (&optional buffer)
+  "Return t if the current buffer is a source block fontify BUFFER.
+
+If BUFFER is nil, the current buffer is used.
+
+This is useful in a `prog-mode' hook to avoid resource-intensive
+features such as `eglot' inside a fontification buffer.
+
+Example:
+  (unless (and (featurep \\='org)
+               (org-src-is-fontify-buffer-p))
+    (eglot-ensure))"
+  (buffer-local-value 'org-src--is-fontify-buffer
+                      (or buffer (current-buffer))))
+
 (defvar org-src-fontify-natively) ; Defined in org.el
 (defun org-src-font-lock-fontify-block (lang start end)
   "Fontify code block between START and END using LANG's syntax.
@@ -678,6 +697,7 @@ as `org-src-fontify-natively' is non-nil."
 	      (erase-buffer)
 	      ;; Add string and a final space to ensure property change.
 	      (insert string " "))
+            (setq org-src--is-fontify-buffer t) ; let the mode know this is a fontify buffer
 	    (unless (eq major-mode lang-mode) (funcall lang-mode))
             (setq native-tab-width tab-width)
             (font-lock-ensure)
-- 
2.47.1

