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?
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
If you cannot use save-excursion
, as @ataylor suggested, then do something like the following. (Presumably you cannot use unwind-protect
either, if the return is not from within a function called by the original function.)
Save point
in a global variable. Save point
as a marker, in case the current buffer changes or the buffer text is modified, making a saved integer position useless.
If possible, wrap the code saving point
with a catch
, and restore the original position in all cases (as with an unwind-protect
).
Use throw
when done with your excursion, to get back to that restoring code (which goes to the marker).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With