Elisp: Saving a position, inserting text before it, and returning to the same location

elisp, emacs

Solution

This is a pretty common need in elisp, so, there's a special form that does it automatically: `save-excursion`. Use it like this:

 (save-excursion
   ;; move about and modify the buffer 
   (do-stuff))
 ;; position restored

Problem

I am currently working on an elisp function that moves to another location, executes a function, then returns to the position. My only problem is that if the function inserts text, the position that I saved is no longer where I want to be. For example, say I have the following string: ``` Hello World ``` And let's say I'm at the 'W' at position 6. And let's say I want to insert another "Hello" to the beginning like this: ``` Hello Hello World ``` The way I'm doing it now, I would store 6 in a variable, insert the hello, then return to position 6. However, now the second hello is at position 6 and I'm returning to the wrong place! Right now I'm doing something like this: ``` (setq my-retloc (point)) (move-function) ``` Then in the end hook of move-function: ``` (do-stuff) (goto-char my-retloc) ``` Unfortunately, doing this in the end hook isn't really avoidable. Is there a way in elisp to make sure that I would return to the correct position?

Original source