From d3b7c9b9212924ceff908d503cc3ad2f3693b345 Mon Sep 17 00:00:00 2001 From: Jethro Kuan Date: Thu, 29 Jul 2021 22:39:24 +0800 Subject: [PATCH] (fix)capture: check for buffer existence before template insertion (#1707) Redefine a new file to Org-roam's capture system as one that does not have a buffer visiting it yet. This means that if a buffer is already visiting the file, then the HEAD template will not be inserted. This is important because Org-roam capture does not enforce the save of files, and this can lead to scenarios where the template is inserted multiple times to a buffer for a file that has not yet been written to disk. --- org-roam-capture.el | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/org-roam-capture.el b/org-roam-capture.el index 0c66f12..100eea4 100644 --- a/org-roam-capture.el +++ b/org-roam-capture.el @@ -528,15 +528,15 @@ also run Org-capture's template expansion." (defun org-roam-capture--goto-location () "Initialize the buffer, and goto the location of the new capture. Return the ID of the location." - (let (p) + (let (p new-file-p) (pcase (or (org-roam-capture--get :if-new) (user-error "Template needs to specify `:if-new'")) (`(file ,path) (setq path (expand-file-name (string-trim (org-roam-capture--fill-template path t)) org-roam-directory)) - (unless (file-exists-p path) - (org-roam-capture--put :new-file path)) + (setq new-file-p (not (org-find-base-buffer-visiting path))) + (when new-file-p (org-roam-capture--put :new-file path)) (set-buffer (org-capture-target-buffer path)) (widen) (setq p (goto-char (point-min)))) @@ -544,9 +544,9 @@ Return the ID of the location." (setq path (expand-file-name (string-trim (org-roam-capture--fill-template path t)) org-roam-directory)) + (setq new-file-p (not (org-find-base-buffer-visiting path))) + (when new-file-p (org-roam-capture--put :new-file path)) (set-buffer (org-capture-target-buffer path)) - (unless (file-exists-p path) - (org-roam-capture--put :new-file path)) (setq p (point-min)) (let ((m (org-roam-capture-find-or-create-olp olp))) (goto-char m)) @@ -555,8 +555,9 @@ Return the ID of the location." (setq path (expand-file-name (string-trim (org-roam-capture--fill-template path t)) org-roam-directory)) + (setq new-file-p (not (org-find-base-buffer-visiting path))) (set-buffer (org-capture-target-buffer path)) - (unless (file-exists-p path) + (when new-file-p (org-roam-capture--put :new-file path) (insert (org-roam-capture--fill-template head t))) (widen) @@ -565,9 +566,10 @@ Return the ID of the location." (setq path (expand-file-name (string-trim (org-roam-capture--fill-template path t)) org-roam-directory)) - (widen) + (setq new-file-p (not (org-find-base-buffer-visiting path))) (set-buffer (org-capture-target-buffer path)) - (unless (file-exists-p path) + (widen) + (when new-file-p (org-roam-capture--put :new-file path) (insert (org-roam-capture--fill-template head t))) (setq p (point-min))