2

I keep on saving various org files in their respective folders using Filename as YYYY-MM-DD.org files . So I ended up typing C-x C-w 2020-10-06.org at least thirty times today. Can this process be automated ?

2 Answers 2

5

I have the following in my .emacs:

;; date
(global-set-key
 "\C-\M-d"
 (lambda (arg) (interactive "P")
   (let ((separator (pcase arg
                      ('(4) "-")
                      (0 "/")
                      (_ ""))))
     (insert
      (format-time-string (concat "%Y" separator "%m" separator "%d"))))))

If I press \C-\M-d, it inserts 20201006 into the active buffer, mini or not. If I prefix it with C-u, it inserts 2020-10-06; prefixing it with M-0 inserts 2020/10/06.

4
  • How can I modify it to put it so that I get 2020-10-06.org
    – Vaibhav
    Oct 6, 2020 at 17:43
  • You should probably use a named function, and format-time-string instead.
    – NickD
    Oct 6, 2020 at 17:46
  • 1
    @NickD: Updated, thanks.
    – choroba
    Oct 6, 2020 at 19:30
  • 2
    @Vaibhav: Replace "%d" by "%d.org". But I use the dates everywhere, not only when creating org files.
    – choroba
    Oct 6, 2020 at 19:31
2

Here's a function that manufactures a filename out of today's time stamp and writes the file out:

(defun write-file-timestamp ()
   (interactive)
   (let ((fname (format-time-string "%Y-%m-%d.org")))
      (write-file fname t)))

The t argument in the write-file call asks for confirmation if the file exists already: you can omit it if you don't care, but it's probably a bad idea, since you are using the same file name in supposedly different directories - but if you make a mistake and you are in the wrong directory, you'll blow away your file without any warning.

You can use the function with M-x write-file-timestamp RET but you will probably want to add a key binding for it:

(global-set-key (kbd "[f12]") #'write-file-timestamp)

to bind it e.g. to the F12 function key.

EDIT: @choroba's answer is a direct reply to your explicit question: it inserts a timestamp into the minibuffer; it also provides a general way of inserting a timestamp anywhere.

This answer is much more limited: it targets only the implied question of automating the writing of files with a name derived from the current date.

3
  • Is there a way to accept two answers. Both the answers provide me the required solution. Thanks for the help.
    – Vaibhav
    Oct 7, 2020 at 3:27
  • No - you gotta choose :-) Personally, I would choose @choroba's solution because it is more general.
    – NickD
    Oct 7, 2020 at 14:35
  • I agree. Thanks for the answer
    – Vaibhav
    Oct 7, 2020 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.