Parsing Time

Emacs Lisp: Inserting to a variable rather than the buffer

I'm still a relatively new elisper, but one thing that I've struggled with is that I often want to call a function that was intended as an interactive function, but from emacs lisp. One recent example of this was org-time-stamp. This function prompts the user for a timestamp using a snazzy calendar interface, and supports lots of lovely features, like being able to enter relative dates (e.g. -2w for two weeks ago). I wanted to use this nice prompt for an elisp function that I was writing to generate an org query string for org-match-sparse-tree.

However, one snag - org-time-stamp inserts the resulting timestamp to a buffer. I needed it in a variable, so that I could substitute it in to the query string. This is because typically it's called interactively, i.e. directly by the user via M-x or otherwise, and in that context it makes a lot of sense. Unfortunately, there's not a built in way to get that timestamp returned as a string from the function rather than inserted into the buffer.

This is when I found a useful little snippet for doing what I needed. It makes use of two functions: with-temp-buffer, which creates a temporary buffer that'll get cleaned up after the function is finished evaluating, and buffer-string, which returns the entire current buffer as a string. Using these two functions together like so lets us capture the value written to buffer, convert it to a string, and then save it to a variable. I'm sure it's something I'll find use for in the future.

(setq test-time
      (with-temp-buffer
        (org-time-stamp nil)
        (buffer-string)))