I have a function for generating a new text file. The file is named automatically from date and time, following this format: yyyy-mm-dd--hh-mm-ss.txt.

However, I also need my function to insert the file name into the first line of the newly made file. The following code is not able to to this, since I am invoking dynamic date and time for both the file name and for the first line in the file. Hence, the text for the file name and for the first line differ by a second or two.

(defun myfun-create-file()
  (find-file-other-frame (format-time-string "C:/Users/me/notes/%Y-%m-%d--%H-%M-%S.txt") )
  (insert (format-time-string "FILE-ID: %Y-%m-%d--%H-%M-%S.txt\n")     )

How can I modify my function, by defining the file name first, as a text string variable, and then inserting this string both to the file name an to the first line of the file?


1 Answer 1


You are looking to create a local variable, which can be done with a let-binding. Here's an example:

(defun myfun-create-file ()
  (let ((stamp (format-time-string "%Y-%m-%d--%H-%M-%S")))
    (find-file-other-frame (concat "C:/Users/me/notes/" stamp ".txt"))
    (insert (concat "FILE-ID: " stamp ".txt\n"))))  

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.