Surprised this one didn't have an answer already! I was just searching before I coded this one up myself... Anyway here's what I'm using:
(defun alec-tangle-from-org-src-buffer ()
"Tangle the file being currently edited in an Org Src buffer."
(interactive)
(when-let ((org-src-minor-mode-p (member 'org-src-mode local-minor-modes))
(file-buf org-src-source-file-name))
;; save-window-excursion
(call-interactively #'org-edit-src-save)
(with-current-buffer (find-file-noselect file-buf)
(call-interactively #'org-babel-tangle))))
(with-eval-after-load 'org-src
(define-key org-src-mode-map (kbd "C-c C-v C-t") #'alec-tangle-from-org-src-buffer)
(define-key org-src-mode-map (kbd "M-SPC o t") #'alec-tangle-from-org-src-buffer))
Explanation: I make sure I'm really in an Org Src buffer and said buffer is associated with a file. The source file name is in the variable org-src-source-file-name
. I didn't verify this, but I believe it is required to save the source block you're editing for changes to be captured in the tangle. Then tangle using a with-current-buffer
block. Works well enough for me!
I also included my keybindings for fun. I made sure org-src
is loaded before trying to bind to org-src-mode-map
.