Save buffer automatically with org-clock-out

Home | About | Items

3 October 2024

Here's a quick one. Some time ago I started using org-mode's clocking features to track my time on various tasks. One small annoyance was that clocking in and out does not automatically save the buffer with the clock. This creates a bit of friction with unexpected prompts to save the buffer before exiting emacs, or before compiles, etc.

So the idea with this fragment is to wrap the call to org-clock-out to automatically save the buffer. While we're at it, we do the same with org-clock-in.

The trick with org-clock-out is that I often use it while viewing a different buffer. With org-clock-in, I'm in the clocking buffer, so the auto-save is simpler. With org-clock-out, we have to capture the buffer before doing the clock out, so we use an :around advice.

(with-eval-after-load 'org
  (advice-add 'org-clock-in :after
              (lambda (&optional select start-time)
                (with-current-buffer (org-clocking-buffer) (save-buffer))))

  (advice-add 'org-clock-out :around
              (lambda (orig &optional switch fail at)
                (let ((b (org-clocking-buffer)))
                  (apply orig switch fail at)
                  (when b (with-current-buffer b (save-buffer)))))))


Contact: @mocom@mastodon.social. Published using C-c C-e P p. If you use this content commercially, kindly make an appropriate donation to Zig Software Foundation in my name.