From edca326d4c8d2fa0c6ae9fe756416f4f78a0c33a Mon Sep 17 00:00:00 2001
From: Mingtong Lin <mt.oss@fastmail.com>
Date: Thu, 4 Dec 2025 22:15:23 -0500
Subject: [PATCH] ob-latex.el: Add option to use #+latex_header in current
 buffer.

* ob-latex.el (org-babel-execute:latex,
  org-babel-latex-buffer-latex-header): Add the
  org-babel-latex-buffer-latex-header option.  If non-nil, the
  #+latex_header property in current buffer will be inserted to the
  preamble of the temporary TeX file for Org Babel LaTeX evaluation.

  It is a common pattern to use Org Babel LaTeX to generate image files
  for LaTeX environments that cannot be directly exported (e.g., for
  HTML export with MathJax).  However, users normally need to duplicate
  content of #+latex_header (for export and preview) in :headers of the
  LaTeX source block.  This patch should help on this.
---
 lisp/ob-latex.el | 27 +++++++++++++++++++++------
 1 file changed, 21 insertions(+), 6 deletions(-)

diff --git a/lisp/ob-latex.el b/lisp/ob-latex.el
index 188ad46a0..f663cc81d 100644
--- a/lisp/ob-latex.el
+++ b/lisp/ob-latex.el
@@ -150,6 +150,15 @@ The following process symbols are recognized:
   :type '(alist :tag "LaTeX to image backends"
 		:value-type (plist)))
 
+(defcustom org-babel-latex-buffer-latex-header nil
+  "If non-nil, use the latex headers in current Org buffer for evaluation.
+
+All the #+LATEX_HEADER in the buffer will be inserted to the preamble
+of the Org Babel LaTeX evaluation."
+  :group 'org-babel
+  :package-version '(Org . "9.8")
+  :type 'boolean)
+
 (defun org-babel-expand-body:latex (body params)
   "Expand BODY according to PARAMS, return the expanded body."
   (mapc (lambda (pair) ;; replace variables
@@ -196,12 +205,18 @@ This function is called by `org-babel-execute-src-block'."
 	    (org-create-formula-image
              body out-file org-format-latex-options in-buffer 'png)))
 	 ((string= "svg" extension)
-	  (with-temp-file tex-file
-	    (insert (concat (funcall org-babel-latex-preamble params)
-			    (mapconcat #'identity headers "\n")
-			    (funcall org-babel-latex-begin-env params)
-			    body
-			    (funcall org-babel-latex-end-env params))))
+	  (let ((buffer-header
+		 (if org-babel-latex-buffer-latex-header
+		     (let ((info (org-export-get-environment (org-export-get-backend 'latex))))
+		       (concat (plist-get info :latex-header) "\n"))
+		   "")))
+	    (with-temp-file tex-file
+	      (insert (concat (funcall org-babel-latex-preamble params)
+			      buffer-header
+			      (mapconcat #'identity headers "\n")
+			      (funcall org-babel-latex-begin-env params)
+			      body
+			      (funcall org-babel-latex-end-env params)))))
 	  (let ((tmp-pdf (org-babel-latex-tex-to-pdf tex-file)))
             (let* ((log-buf (get-buffer-create "*Org Babel LaTeX Output*"))
                    (err-msg "org babel latex failed")
-- 
2.39.5 (Apple Git-154)

