Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

emacs

elisp

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?

like image 317
user1539179 Avatar asked Feb 21 '14 22:02

user1539179


2 Answers

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
like image 135
ataylor Avatar answered Nov 15 '22 09:11

ataylor


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.)

  1. 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.

  2. If possible, wrap the code saving point with a catch, and restore the original position in all cases (as with an unwind-protect).

  3. Use throw when done with your excursion, to get back to that restoring code (which goes to the marker).

like image 36
Drew Avatar answered Nov 15 '22 10:11

Drew