Auto-saving Org Archive File

For note taking and TODO tracking, I use org mode for Emacs. When a TODO item is archived in an org buffer, it moves to a special archive file. This article is about how to automatically save the archive buffer after each item is archived.

When an item is archived, the archive file opens in a buffer, but the buffer isn’t saved. I find it annoying that I have to make special effort to save the archive file every time I archive something. This behavior could result in data loss if one neglects to save the archive file. Apparently “org-mode used to save that archive file after each archived item” [0]. I decided to re-implement that behavior in my own Emacs configuration.

Depending on your org setup, this can be accomplished relatively easily using save-some-buffers and advice-add.

;; I have my primary org document's file name defined as a constant for use in
;; other parts of my config. 
(defconst notes-file "~/Documents/notes.org")

;; When an item is archived, it's saved to a file named
;; `<source-org-file>_archive`, so here I similarly define a constant for that
;; archive file.
(defconst notes-archive-file (concat notes-file "_archive"))

;; The `save-some-buffers` function can run silently, and it also accepts a
;; function argument to predicate whether a buffer is saved or not.
;; This predicate simply says "save the buffer's file if it's the notes archive
;; file"
(defun save-notes-archive-file ()
  (interactive)
  (save-some-buffers 'no-confirm (lambda ()
                                   (equal buffer-file-name
                                          (expand-file-name notes-archive-file)))))

;; Finally, the newly-defined function can advise the archive function. So,
;; after a subtree in org is archived, the archive file will be automatically saved.
(advice-add 'org-archive-subtree :after #'save-notes-archive-file)

References: