In this answer, I use a regular expression search/replace to convert from one type of ruby block to another. However, after the function ruby-flip-containing-block-type is done, the point is moved to the beginning of the replaced text, even though there is a save-excursion around the function.
I even tried saving the point to a register and jumping back to it after the flip. The saved point is relocated to the beginning of my changes. After some google searches, I think the problem lies with the fact that the replace-match call updates the buffer contents at the original point.
Any ideas on how I can preserve/restore the original location of the point in this situation?
When text is replaced, the old text is removed, and the new text inserted. So let’s say the buffer looks like this, where
-!-indicates the position of point:Suppose you replace
jklmnopwithjlkMnop. First thejklmnopis removed:and then the
jlkMnopis inserted:You can see that the effect is as if point was moved.
The way to preserve point is to be much more careful about how you go about replacing the text. Instead of replacing big blocks (which might well contain point), replace only the small sections that actually change. In the answer you link to, instead of replacing
do\(.*\)endwith{\1}, replace thedowith{and theendwith}in separate replacements.This doesn’t have to be ugly. Perhaps something like this, using the fifth (
subexp) argument toreplace-match: