我在写一个函数,用于改进query-replace的默认行为,即在执行query-replace的时候,会默认选中光标下的word,我现在的问题是,例如我的光标在word
这个单词下面,当我执行函数的时候,可以在mini buffer下显示,you want to replace word
with:,就是交互的时候,可以提示选中的单词,但是我查了一下emacswiki关于interactive
的用法,没有找到想要的结果,所以现在只能是用固定的提示语句。
也可以参考我的代码,如果需要选中的话可以使用 region 的方式来取词,需要修改代码。
(defun test-put-prompt (arg)
(interactive
(let ((word-start (save-excursion
(progn
(backward-word)
(point))))
(word-end (save-excursion
(progn
(forward-word)
(point)))))
(list (read-string (format "You want to replace '%s' with: "
(buffer-substring-no-properties word-start word-end))))))
(message "Your input word is '%s'" arg))
只能说下自己的思路(下午要去考试
interactive 里可以写一个返回字符串的表达式, 通过 save-excursion 取到单词的开始,结束位点, 然后(buffer-substring-no-properties start stop) 能取到字符串,写好了可以贴出来分享一下~
我也突然想到一种实现方法,测试可以
(defun query-replace-dwim (replace-str)
(interactive
(list (let ((replaced-string (if (region-active-p)
(buffer-substring-no-properties
(region-beginning)
(region-end))
(thing-at-point 'symbol))))
(read-string (format "Do query-replace %s with:" replaced-string)))))
(save-excursion
(let ((substring (if (region-active-p)
(buffer-substring-no-properties
(region-beginning)
(region-end))
(thing-at-point 'symbol))))
(goto-char (point-min))
(query-replace substring replace-str))))
推荐个包 anzu,里面有你要的功能:
anzu-query-replace-at-cursor Same as anzu-query-replace except from-string is symbol at cursor
anzu-query-replace-at-cursor-thing Same as anzu-query-replace-at-cursor except replaced region is specified by anzu-replace-at-cursor-thing.
anzu-replace-at-cursor-thing Same as anzu-query-replace-at-cursor-thing except not query. This command is useful in refactoring such as changing variable name in the function.
也有对应的evil版本 evil-anzu
其实我只是想增强一下query-replace的默认行为。anzu的操作,我也可以用occur+evil-multiedit来实现
.我觉得我上面写的函数也达到我想要的结果了。因为anzu这种query-replace适合是全部都replace的,但是如果我只是想将第一个和第三个匹配的单词替换,似乎anzu不行,如果是我的函数的话,应该可以query-replace-dwim RET
然后y n y
就行了,如果想全部代替,按!
就好了。我的个人见解:relaxed: