Add CREATED date property to TODOs in org-mode - emacs

I read the org-mode manual but couldn't find an easy way to add a CREATED field to newly created TODOs. In combination with org-log-done one could then compute the time it took to close a particular TODO. This is especially useful when using archive files.
Example:
* TODO Do something
CREATED: [2012-09-02 Sun 23:02]
* DONE Do something else
CREATED: [2012-09-02 Sun 20:02]
CLOSED: [2012-09-02 Sun 22:02]
I would expect the CREATED field to be added to new tasks (tasks which don't have that field) whenever the file is saved.
Any suggestions on how to achieve this? Using something like Git is not a solution for me to track the creations of TODOS.

I use org-expiry to implement that functionality, which is in the contrib directory of org.
The base configuration I use is:
;; Allow automatically handing of created/expired meta data.
(require 'org-expiry)
;; Configure it a bit to my liking
(setq
org-expiry-created-property-name "CREATED" ; Name of property when an item is created
org-expiry-inactive-timestamps t ; Don't have everything in the agenda view
)
(defun mrb/insert-created-timestamp()
"Insert a CREATED property using org-expiry.el for TODO entries"
(org-expiry-insert-created)
(org-back-to-heading)
(org-end-of-line)
(insert " ")
)
;; Whenever a TODO entry is created, I want a timestamp
;; Advice org-insert-todo-heading to insert a created timestamp using org-expiry
(defadvice org-insert-todo-heading (after mrb/created-timestamp-advice activate)
"Insert a CREATED property using org-expiry.el for TODO entries"
(mrb/insert-created-timestamp)
)
;; Make it active
(ad-activate 'org-insert-todo-heading)
If you are using capture it does not automatically work and needs a little glue. I have posted the complete config here: https://gist.github.com/4037694

A more lightweight solution would be to add ! flag to the TODO state:
(setq org-todo-keywords '((sequence "TODO(!)" "DONE")))
Then:
* TODO get of your ass
- State "TODO" from [2016-06-03 to. 10:35]
It isn't very pretty though.
Ref: http://orgmode.org/org.html#Tracking-TODO-state-changes

You don't need to modify functions with 'defadvice' to run expiry code on capture.
You should use hook:
(add-hook 'org-capture-before-finalize-hook
(lambda()
(save-excursion
(org-back-to-heading)
(org-expiry-insert-created))))
Same for 'org-insert-todo-heading'. There is a hook:
(add-hook 'org-insert-todo-heading-hook
(lambda()
(save-excursion
(org-back-to-heading)
(org-expiry-insert-created))))

Org provides a hook org-after-todo-state-change-hook which you can use here:
org-after-todo-state-change-hook is a variable defined in ‘org.el’.
Documentation:
Hook which is run after the state of a TODO item was changed.
The new state (a string with a TODO keyword, or nil) is available in the
Lisp variable ‘org-state’.
Use it as follows:
(require 'org-expiry)
(add-hook 'org-after-todo-state-change-hook
(lambda ()
(when (string= org-state "TODO")
(save-excursion
(org-back-to-heading)
(org-expiry-insert-created)))))
org-expiry is part of org-contrib, which is included in the org-plus-contrib package on the org ELPA.

Here's a buried treasure:
(setq org-treat-insert-todo-heading-as-state-change t)
I found it here, in response to someone saying they wanted an org-insert-todo-heading-hook.
Just tried it out and, true to form, when you org-insert-todo-heading, it counts as a state change, so ex: #+TODO: TODO(t!) | ... will add a log.

If you create all your TODOs with org-capture the following capture template does the trick:
(setq org-capture-templates
'(
("t" "TODO Task" entry (file+headline "~/inbox.org" "Tasks")
"* TODO %?\nCREATED: %u\nSRC: %a\n%i\n")
))
The result will look something like this:
* Tasks
** TODO Dummy task
CREATED: [2015-05-08 Fri]
SRC: [[file:~/path/to/file/where/you/created/the/task.org::*heading"][heading]]

Here is a lightweight solution that does not require an external package. I got it from the answer by #MarcinAntczak, the comments by #Clément, and this similar thread. It works with org-capture and with M-S-RET. Put this in your Emacs initialization file (e.g. ~/.emacs):
(defun insert-created-date(&rest ignore)
(insert (format-time-string
(concat "\nCREATED: "
(cdr org-time-stamp-formats))
))
(org-back-to-heading) ; in org-capture, this folds the entry; when inserting a heading, this moves point back to the heading line
(move-end-of-line()) ; when inserting a heading, this moves point to the end of the line
)
; add to the org-capture hook
(add-hook 'org-capture-before-finalize-hook
#'insert-created-date
)
; hook it to adding headings with M-S-RET
; do not add this to org-insert-heading-hook, otherwise this also works in non-TODO items
; and Org-mode has no org-insert-todo-heading-hook
(advice-add 'org-insert-todo-heading :after #'insert-created-date)
I did not add this function to state changes (e.g., from plain heading to TODO) because it would need to be in a properties drawer and I prefer to not have those extra lines. If you prefer to have it in properties, use the function defined in see this thread.

You can add a time stamp at creation time with zero config, but it won't be labeled CREATED. Rather than manually typing TODO, use C-c C-t. It will then be logged as "state changed to TODO from """ and time stamped.

Related

Insert yasnippet by name

I want to insert a specific yasnippet as part of a function in emacs-lisp. Is there a way to do that?
The only command that seems related is yas/insert-snippet, but it simply opens a popup with all the options and the documentation doesn't say anything about bypassing the popup by specifing the snippet name.
yas/insert-snippet is indeed just a thin wrapper around yas/expand-snippet for interactive use. However, the internal structures are... interesting. Judging from the source code the following does work for me when I want to expand the "defun" snippet in elisp-mode:
(yas/expand-snippet
(yas/template-content (cdar (mapcan #'(lambda (table)
(yas/fetch table "defun"))
(yas/get-snippet-tables)))))
As the author of yasnippet, I think you'd rather not rely on internal details of yasnippet's interesting data structures, which may change in the future. I would do this based on the documentation of yas/insert-snippet and yas/prompt-functions:
(defun yas/insert-by-name (name)
(flet ((dummy-prompt
(prompt choices &optional display-fn)
(declare (ignore prompt))
(or (find name choices :key display-fn :test #'string=)
(throw 'notfound nil))))
(let ((yas/prompt-functions '(dummy-prompt)))
(catch 'notfound
(yas/insert-snippet t)))))
(yas/insert-by-name "defun")
I'm just getting into yasnippet and I wanted to automatically insert one of my snippets upon opening a new file for certain modes. That led me to here but I've generated a slightly different solution. Providing yet another alternative: ("new-shell" is the name of my personal snippet for providing a new shell script template)
(defun jsm/new-file-snippet (key)
"Call particular yasnippet template for newly created
files. Use by adding a lambda function to the particular mode
hook passing the correct yasnippet key"
(interactive)
(if (= (buffer-size) 0)
(progn
(insert key)
(call-interactively 'yas-expand))))
(add-hook 'sh-mode-hook '(lambda () (jsm/new-file-snippet "new-shell")))
IMO, my solution is a tad less susceptible to breaking should yasnippet change dramatically.
This is 2022 now, so we can simply do the following :
(yas-expand-snippet (yas-lookup-snippet "name-of-your-snippet"))
See the documentation

Interactively enter headline under which to place an entry using capture

Using capture templates like the one below, I can add entries to different headlines in a file. How can I manually enter a headline during capture, instead of setting up each headline to a key in the .emacs file like I am now doing?
(setq org-capture-templates
'(
("l" "Log" entry
(file+headline "c:/Org/log.org" "Log")
"\n\n** %?\n<%<%Y-%m-%d %a %T>>"
:empty-lines 1))
It looks like, in newer versions of org at least, that custom functions can be used in capture templates to do this.
Instead of:
entry
(file+headline "~/Work/work.org" "Refile")
You can use:
entry
(file+function "~/Work/work.org" function-finding-location)
Where 'function-finding-location' is a custom function you have written yourself, which could easily prompt you for a headline.
Or, you can go even farther, and define a custom function which will prompt for both file name and headline name (or anything else you can dream up):
entry
(function function-finding-location)
I don't really know enough elisp to write these functions myself, but this looks like the place to start. It'd be nice if someone else could offer up some code. The relevant documentation is here:
http://orgmode.org/manual/Template-elements.html
I wrote a function to be used with file+function which will prompt for a location on capture.
It uses the internal prompting function of org-refile so we get completions of headings in the prompt (with maxlevels overridden to 9). When the user enters an unknown heading, it creates it at the end of the file.
(defun org-ask-location ()
(let* ((org-refile-targets '((nil :maxlevel . 9)))
(hd (condition-case nil
(car (org-refile-get-location nil nil t t))
(error (car org-refile-history)))))
(goto-char (point-min))
(outline-next-heading)
(if (re-search-forward
(format org-complex-heading-regexp-format (regexp-quote hd))
nil t)
(goto-char (point-at-bol))
(goto-char (point-max))
(or (bolp) (insert "\n"))
(insert "* " hd "\n")))
(end-of-line))
In your case, you use it like this:
(setq org-capture-templates
'(("l" "Log" entry
(file+function "c:/Org/log.org" org-ask-location)
"\n\n** %?\n<%<%Y-%m-%d %a %T>>"
:empty-lines 1))
I don't believe you can have it prompt for the headline on capture. You can however refile from within the capture window which should result in the desired behaviour.
I would define a catch-all target headline/file so that if you forget you will always collect them in the same location and then just have to refile them once created. If you also set a category/tag on this headline you will be able to easily see the misfiled capture entry and refile it as desired. (Example below)
Then instead of finishing with C-c C-c choose to refile with C-c C-w and you will be asked to select the headline you want to send the new entry to.
The capture template I use for this catch all is as follows (adapted from Bernt Hansen's capture settings)
("i"
"Incidents"
entry
(file+headline "~/Work/work.org" "Refile")
"* TODO %^{Ticket} - %^{User}\nSCHEDULED: %^t DEADLINE: %^t\n:PROPERTIES:
\n:DATE: %^U\n:END:\n%^{MANAGER}p%^{HOSTNAME}p%^{LOCATION}p%^{TEL}p\n%c"
:empty-lines 1 :clock-in t :clock-resume t)
(Line breaks are added to avoid scrolling when reading here)
The heading is configured as follows
* Refile :refile:
:PROPERTIES:
:CATEGORY: Unsorted
:END:
With this I end up with all non-refiled tasks showing up as
Unsorted: Deadline: TODO <Headline> :refile::
I currently tend to use tags as reference if I'm waiting for coworkers/managers to deal with the ticket, or to remind me to speak to them about it when I see them so the tag at the end stands out clearly, as does Unsorted if I'm trying to remember what the issue is (since I simply have a case number and user name showing, details within the entry).
while capturing a note, after finishing writeup press C-u C-c C-w to refile under desired new headline.
you also need to set this variable
(setq org-refile-allow-creating-parent-nodes (quote confirm))
you can set it to t instead of confirm. But I like it be confirm because I dont often refile to new targets

How to archive all the DONE tasks using a single command

To archive the DONE tasks i am using
C-c C-x a
command. The draw back is i have to manually move over the DONE tasks one by one and then archive it.
How to archive all the DONE tasks using a single command.
You can bulk archive (or refile/change todo etc) from within the Agenda view.
http://orgmode.org/manual/Agenda-commands.html#Agenda-commands
If you call Org-Agenda from within the buffer you want to archive you can temporarily restrict it to only that buffer and view only todo entries and filter for only DONE
C-c a < t
N r
Where N corresponds to the shortcut for your DONE state (with default states it would be 2)
Then you'd simply need to mark all the desired headlines and bulk archive
m (mark for bulk action)
B a (or B $ for arch->sibling)
Here's a corrected version of madalu's snippet. Note that this version also only operates on the current subtree (change 'tree back to 'file to operate over the entire file).
(defun org-archive-done-tasks ()
(interactive)
(org-map-entries
(lambda ()
(org-archive-subtree)
(setq org-map-continue-from (org-element-property :begin (org-element-at-point))))
"/DONE" 'tree))
You can write a function using org-map-entries:
(defun my-org-archive-done-tasks ()
(interactive)
(org-map-entries 'org-archive-subtree "/DONE" 'file))
Also from http://orgmode.org/manual/Moving-subtrees.html#Moving-subtrees
C-u C-c C-x C-s
Check if any direct children of the current headline could be moved to the archive. To do this, each subtree is checked for open TODO entries. If none are found, the command offers to move it to the archive location. If the cursor is not on a headline when this command is invoked, the level 1 trees will be checked.
There is now a command org-archive-all-done that is built into org-mode, and in org-archive.el.
If you want to do it in the source Org buffer (as opposed to in an Org agenda view), and if they are following each other, you can select all of them in a region, and apply a command (such as C-c C-t d).
Only setting needed:
;; Some commands act upon headlines in the active region.
(setq org-loop-over-headlines-in-active-region 'start-level)
I found the direct "org-map-entries" method in a couple of these answers to be a little "fragile" for some reason in situations with more varied nesting and TODOs at multiple levels.
This method - generating a list and then archiving in reverse (to avoid changes in positioning) seems to cover every use case I've thrown at it. Sharing it here for anyone else that runs into trouble.
Note the "TODO" string match on the last line needs to match how you have your TODOs defined exactly (for example in a vanilla case, the match may be: "TODO=\"DONE\"").
(defun org-archive-done-tasks ()
"Archive all tasks marked DONE in the file."
(interactive)
(mapc (lambda(entry)
(goto-char entry)
(org-archive-subtree))
(reverse (org-map-entries (lambda () (point)) "TODO=\"★ DONE\"" 'file))))
Based on Robert's Answer
(require 'org)
(require 'org-archive)
(add-hook 'org-mode-hook (lambda () (add-hook 'after-save-hook 'org-archive-all-done nil t)))

Get a list of all tags in emacs

Is there a way to get all of the tags from the files defined in your tags table list? I've set my tags file like this:
(setq tags-table-list '("~/project/TAGS"))
I've tried (tags-completion-table), but it doesn't contain all the tags.
If you got only one TAGS file, M-x visit-tags-table ~/project/TAGS or (visit-tags-table "~/project/TAGS") should load the TAGS table into a buffer which means it becomes accessible to Emacs in the same way it would be used for, M-x tags-search.
If you add more TAGS files to the project or have more than one project, (setq tags-table-list '("~/project1/TAGS" "~/Project2/TAGS" ...)) and doing (visit-tags-table-buffer t) should visit the next table each time it is called, until the end of the list.
EDIT:
(defvar buffer-in-string)
(defvar string-list)
(defun write-buffer-to-string ()
(interactive)
(setq buffer-in-string (buffer-substring (point-min) (point-max)))
(kill-buffer) ;; If the buffer is big, it makes sense to kill it,
;; since its contents are copied into the string anyway
(setq string-list (split-string buffer-in-string " "))
)
That should bring the buffer into a string. There should be a more elegant way, but at the moment, this is the most I could write with my very limited elisp fluency.
Function tags-completion-table gives you a completion table to use. From the doc string:
Build 'tags-completion-table' on demand.
The tags included in the completion table are those in the current
tags table and its (recursively) included tags tables.
And tags-lazy-completion-table gives you a completion function to use. It uses tags-completion-table.

How to configure cleverly org-archive-location in org-mode

BACKGROUND: In org-mode, the variable org-archive-location is set to "%s_archive::" by default, so that a file "toto.org" archives into a file "toto.org_archive". I would like it to archive to "toto.ref" instead. I am using org-mode version 7.4 (out of the git server).
I would have thought it to be as simple as
(setq org-archive-location
`(replace-regexp-in-string ".org" ".ref" %s)
)
But I was pointed out that this was not proper in LISP (plus, it did not work). My final solution is as follow, you should be able to adapt to most clever configurations of org-archive-location:
(setq org-archive-location "%s::* ARCHIVES")
(defadvice org-extract-archive-file (after org-to-ref activate)
(setq ad-return-value
(replace-regexp-in-string "\\.org" ".ref" ad-return-value)
)
)
Note that:
1) I voluntarily did not add a $ at the end of ".org" so that it would properly alter "test.org.gpg" into "test.ref.gpg".
2) It seems that one should use the regular expression "\.org" (rather than, say, ".org") (longer explanation below in the answers).
You can't define a variable in Emacs such that its value is obtained by running code; variables have simple, static values.
You can achieve the effect you described by advising the function org-extract-archive-file, which is the one that generates an archive location from org-archive-location:
(defadvice org-extract-archive-file (after org-to-ref activate)
(setq ad-return-value
(replace-regexp-in-string "\\.org" ".ref" ad-return-value)))
This works for me now, but of course the internals of org-mode are subject to change and this solution may not work forever.
You should not quote an expression that you want to evaluate. Note also that in a regular expression, . matches any character.
Here is an example of how to set the file, the location (e.g., main heading) in the file, and whether or not to include additional archive information:
(let* (
(org-archive-location "~/todo.org::* TASKS")
(org-archive-save-context-info nil))
...)
You can try this: #+ARCHIVE: %s.ref:: at the beginning of your org file.
Read more about it here.
Also, other interesting option is to set inside your headtree the following, for instance:
* Main Header of tree
:PROPERTIES:
:ARCHIVE: toto.ref:: * Main Header of tree in archive file
:END:
** sub tree of main header and so on
The latter I took from this video.