0

I am using the following function to make a new text file containing premade rows. The text file is named with a date and time tag, and stored in a /notes/ folder.

(defun myfun-create-file-with-rows()
  (interactive)
  (find-file (format-time-string "C:/Users/myUser/notes/%Y-%m-%d--%H-%M-%S.txt"))
  (insert "My title\n\n\n\n\n\nLinks:\n")
  )

The function inserts the row "My title" followed by 5 blank rows and the row "Links:".

When I use this function the position of the cursor (point) ends at the bottom of the inserted lines, below the row "Links:". How can I make the cursor end a line below the row "My title" ?

1

When constructing the contents of a particular buffer (or portion thereof), it is helpful to think about storing one or more locations (e.g., a buffer position) that may be needed later on in the function. Sometimes a location needs to be calculated or searched for. We could have inserted all of the text and then searched backwards for "My title", but that seems like extra work.

The function save-excursion is used frequently to return to a particular location. After inserting "My title\n", we are at the desired location specified by the original poster in the question above. By wrapping save-excursion around the text being inserted after "My title\n", Emacs will place point back at that same location when the insertion is complete.

(defun myfun-create-file-with-rows ()
  "Doc-string."
  (interactive)
  (find-file (format-time-string "C:/Users/myUser/notes/%Y-%m-%d--%H-%M-%S.txt"))
  (insert "My title\n")
  (save-excursion
    (insert "\n\n\n\n\nLinks:\n")))
| improve this answer | |
  • a little bit of text explaining how this works would be welcome here. – Stefan Jul 10 '19 at 19:05
  • Thanks or your answer, it solves my problem perfectly! – myotis Jul 15 '19 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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