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

别等时光非礼了梦想. 提交于 2019-12-10 14:54:10

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/21946623/elisp-saving-a-position-inserting-text-before-it-and-returning-to-the-same-lo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!