问题描述
我目前正在使用一个移动到另一个位置的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
让我们说我在位置6处的W。我们假设我想像这样插入另一个Hello:
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
现在我正在做这件事,我将把6存储在一个变量中,插入你的hello,然后返回到位置6.然而,现在第二个hello是在第6个位置,我返回到错误的地方!
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)
最后钩子的移动功能:
(do-stuff)
(goto-char my-retloc)
不幸的是,在最后的钩子中这样做并不是真正可以避免的。有没有办法在elisp中确保我会回到正确的位置?
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?
推荐答案
这是elisp中很常见的需求,所以有一个特殊的表单可以自动执行:保存冲程
。使用它像这样:
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
这篇关于Elisp:保存位置,在其前面插入文本,并返回到同一位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!