I don’t know why I haven’t shared this little helper before, but here it is.
(defun mu-date-at-point (date)
"Insert current DATE at point via `completing-read'."
(interactive
(let* ((formats '("%Y%m%d" "%F" "%Y%m%d%H%M" "%Y-%m-%dT%T"))
(vals (mapcar #'format-time-string formats))
(opts
(lambda (string pred action)
(if (eq action 'metadata)
'(metadata (display-sort-function . identity))
(complete-with-action action vals string pred)))))
(list (completing-read "Insert date: " opts nil t))))
(insert date))
What mu-date-at-point
does is formatting the current date in four different ways with format-time-string
and then offering them as options to completing-read
.
The interesting part is how opts
is built. It’s a nice trick to ensure its content is always sorted according to the order in formats
. Without leveraging completion-metadata
the completion system would take care of sorting the items for me.
For the record, I learned how to tweak completion-metadata
on Emacs StackExchange. I suggest reading C-h f completing-read
and C-h f completion-metadata
to know more.