替换匹配后,通过保存偏移丢失光标位置 [英] Losing cursor location with save-excursion after replace-match

查看:85
本文介绍了替换匹配后,通过保存偏移丢失光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个答案,我使用正则表达式搜索/替换将红宝石块从一种类型转换为另一种类型。但是,完成函数 ruby​​-flip- Containing-block-type 之后,即使存在<$ c,该点也会移到替换文本的开头。 $ c> save-excursion 围绕函数。

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.

我什至尝试将点保存到寄存器中,并在翻转后跳回该寄存器。保存的点将重新定位到我的更改的开始。在经过一些Google搜索之后,我认为问题出在替换匹配调用在原始点更新缓冲区内容这一事实。

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:

abcdefghijklm-!-nopqrstuvwxyz

假设您替换 jklmnop jlkMnop 。首先删除 jklmnop

Suppose you replace jklmnop with jlkMnop. First the jklmnop is removed:

abcdefghi-!-qrstuvwxyz

然后插入 jlkMnop

abcdefghi-!-jklMnopqrstuvwxyz

您可以看到效果就像移动了点。

You can see that the effect is as if point was moved.

保存点的方法是要更加谨慎地替换文本。而不是替换大块(可能包含点),而仅替换实际更改的小部分。在答案中,您链接到,而不是用 {\1} do\(。* \)end c>,将 do 替换为 { end } 分开替换。

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\(.*\)end with {\1}, replace the do with { and the end with } in separate replacements.

这没有很难看也许是这样,将第五个( subexp )参数用于 替换匹配

This doesn't have to be ugly. Perhaps something like this, using the fifth (subexp) argument to replace-match:

(when (re-search-forward "\\(do\\).*\\(?:\n.*\\)\\(end\\)" nil t)
  (replace-match "}" t t nil 2)
  (replace-match "{" t t nil 1))

这篇关于替换匹配后,通过保存偏移丢失光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆