query-replace无法完成文本替换

各位使用emacs的朋友:

你们好!

我之前没有用过emacs的文本替换功能,这两天在处理纯文本文件,开始有这方面的需要,但是当我尝试进行替换的时候,不管怎么输入,都是显示:replaced 0 occurrences。我在emacs -q状态下也尝试了,问题依旧存在。而且,确认该问题与文本是中文还是英文没有关系。

我的使用环境是:linux mint 22.3;emacs 30.2,自己手动编译,但没有更改或添加任何参数;文本编码为utf-8。

在emacs -q下测试使用这段文本,目标将to替换为into:

Attempts to retrieve or share EMACS information not necessary to perform your job duties are strictly prohibited. Unauthorized access may result in disciplinary action, up to and including termination and …

祝好!

Yiyuan

可能是操作问题,能否录一段执行替换操作的 gif?

1 个赞

试着追踪一下 lisp/replace.elperform-replace 函数的 replace-count 这个变量?

应该是操作问题,你没选中,直接做执行M-%了。实际是先C-space做选中再M-%,然后按下y确定。不想选中后操作尝试使用visual-replace,这个操作更丝滑。

抱歉,我又测试了下,光标的位置还挺重要。。。 :joy:

谢谢你的回复,我再次尝试的过程中发现了问题:

query-replace替换的范围是从当前光标所在位置一直到末尾,如果在这段区域内存在要被替换的文本,在输入替换文本并回车之后,就会进入替换模式,即高亮光标原始位置至末尾区域内所有被替换文本,然后将光标移动到第一个文本处,由用户按下空格键确认替换。一处替换完之后光标会自动跳至第二处,继续重复上述步骤。

特别要注意的是:在原始光标位置之前出现的被替换文本,在输入被替换文本这一参数(即第一个输入的字符串)时,会被高亮。但是在正式进行替换的过程中,就会被忽略。我应该就是栽在这里了。

1 个赞

下次记得先看文档吧

你好:

我确实看文档了,但是我的实际使用情境是根本就没有出现文档中提到的“one by one”的情境,输入完第二个参数回车之后直接就替换结束,返回replaced 0 occurrences。所以对照文档我根本不知道它在说什么。

祝好!

可以使用 ! 一次性完成所有替换,但是要谨慎使用。(当然可以回撤)

来自 C-h k M-%

M-% runs the command query-replace (found in global-map), which is an interactive native-comp-function in ‘replace.el’.

It is bound to M-% and %. It can also be invoked from the menu: Edit → Replace → Replace String…

(query-replace FROM-STRING TO-STRING &optional DELIMITED START END BACKWARD REGION-NONCONTIGUOUS-P)

Inferred type: (function (t t &optional t t t t t) t)

Replace some occurrences of FROM-STRING with TO-STRING. As each match is found, the user must type a character saying what to do with it. Type SPC or ‘y’ to replace the match, DEL or ‘n’ to skip and go to the next match. For more directions, type C-h at that time.

In Transient Mark mode, if the mark is active, operate on the contents of the region. Otherwise, operate from point to the end of the buffer’s accessible portion.

In interactive use, the prefix arg (non-nil DELIMITED in non-interactive use), means replace only matches surrounded by word boundaries. A negative prefix arg means replace backward.

Use M-n to pull the last incremental search string to the minibuffer that reads FROM-STRING, or invoke replacements from incremental search with a key sequence like C-s C-s M-% to use its current search string as the string to replace.

加粗的这一段:“ 在 Transient Mark 模式下,如果标记(mark)处于激活状态,则对区域(region)的内容进行操作。否则,操作范围将从光标位置(point)始终延伸至缓冲区(buffer)可访问部分的末尾。”

确实藏得有一点深,不过其实讲得非常明白了

1 个赞

谢谢,我在文档中看到了。

感谢你的提醒!

我当时是用网页搜索的query replace完整的文档,其内容对于初学者来说冗余信息有点多,又刚好与我的实践(即我误判它应该是单次全量替换)不一致,所以我才想到来论坛求助。很抱歉占用了大家的时间。

这个问题之前一天遇到800次, 现在已经有心理阴影了, 一个命令没有按直觉发挥作用,先看看光标是不是没放对地方, 或者是不是region没选中 :smiling_face_with_tear: