I'd like to track my deep work so I've thought about adding a hook to org-clock-out-hook to achieve this.
(defun my/clock-out-deep-work () (when (yes-or-no-p "Was that a deep work session?") ... (org-capture nil "d") )) (add-hook 'org-clock-out-hook 'my/org-clock-out-hook) I'm having trouble formulating the rest of the function which I'd like to be setting variables to be parsed to a org capture template to add the data to an org table. Namely, I want the duration for the last clock session (not the total time spent on the task) to be set to the variable org-clocked-duration. This is the template below
("d" "Deep Work Task" table-line (file ,(concat org-directory "deep_work.org")) "| %U | %(identity org-clocked-duration) | %K | %^{Activty Type} | %^{Location} | %? |" :unnarrowed t ) I keep the org clock data in the logbook drawer (i.e. org-log-into-drawer set to true) which means I can't use (org-entry-get nil "CLOCK"). I am on org mode version 9.6, emacs version 28.2 running Doom Emacs (issue unrelated to doom however)
Solution with help of answer below
Here is the solution that works for me thus far:
(defun my/last-duration () (let* ((e (org-element-at-point)) (type (org-element-type e))) (when (and (eq type 'drawer) (string= (org-element-property :drawer-name e) "LOGBOOK")) (let ((contents-beg (org-element-property :contents-begin e))) (save-excursion (goto-char contents-beg) (let* ((e (org-element-at-point)) (type (org-element-type e))) (when (eq type 'clock) (org-element-property :duration e)))))))) (defun my/get-last-clocked-task () "Get the name of the last clocked task." (save-excursion (goto-char (car org-clock-history)) (let ((title-with-props (org-get-heading t)) (keyword (org-get-todo-state))) (substring-no-properties title-with-props (if keyword (1+ (length keyword)))) ) )) (defun my/org-clock-out-hook () "Run after clocking out of a task to display time clocked in." (when (yes-or-no-p "Was that a deep work session?") (save-excursion (org-back-to-heading) (search-forward ":LOGBOOK:" nil t) (let* ((org-clocked-duration (my/last-duration)) (org-last-clocked-task (my/get-last-clocked-task)) (org-capture-templates `(("d" "Deep Work Task" table-line (file ,(concat org-directory "deep_work.org")) "| %U | %(with-current-buffer (org-capture-get :original-buffer) org-clocked-duration) | %(identity org-last-clocked-task) | %^{Activty Type} | %^{Location} | %? |" :unnarrowed t ))) ) (org-capture nil "d")) ) )) (add-hook 'org-clock-out-hook 'my/org-clock-out-hook)