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" ?

myotis
  • 1,099
  • 1
  • 13
  • 27

1 Answers1

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")))
lawlist
  • 18,826
  • 5
  • 37
  • 118