给出以下代码示例:
uint8_t i,in,ni; i = in = 2; ni = 1; while (2 == i > ni) in++;
如何使用emacs,vi,* nix命令或其他任何东西分别用in,ni和i或inni,inin和nini替换i,in和ni?
如果我没有弄错的话,到目前为止提供的解决方案(使用Perl和Vim)在任何替换都是要替换的后一个词中时不能正常工作.特别是,没有一个解决方案适用于第一个例子:“i”将被替换为“in”,然后将被错误地替换为“ni”,然后通过后续规则返回“i”,而它应该保留作为“在”.
替换不能独立承担并连续应用;它们应该并行应用.
在Emacs中,您可以这样做:
M-xparallel更换,
并在提示符下输入
我在ni ni ni.
替换将发生在光标和缓冲区的末尾之间,或者在一个区域中(如果选择了一个).
(如果你在〜/ .emacs.d / init.el中有这个定义:-)
(require 'cl) (defun parallel-replace (plist &optional start end) (interactive `(,(loop with input = (read-from-minibuffer "Replace: ") with limit = (length input) for (item . index) = (read-from-string input 0) then (read-from-string input index) collect (prin1-to-string item t) until (<= limit index)),@(if (use-region-p) `(,(region-beginning),(region-end))))) (let* ((alist (loop for (key val . tail) on plist by #'cddr collect (cons key val))) (matcher (regexp-opt (mapcar #'car alist) 'words))) (save-excursion (goto-char (or start (point))) (while (re-search-forward matcher (or end (point-max)) t) (replace-match (cdr (assoc-string (match-string 0) alist)))))))
编辑(二零一三年八月二十零日):
一些增强功能:
>对于只给出两个项目的特殊情况,改为执行交换(即相互替换);
>以与查询替换相同的方式要求确认每次更换.
(require 'cl) (defun parallel-query-replace (plist &optional delimited start end) "Replace every occurrence of the (2n)th token of PLIST in buffer with the (2n+1)th token; if only two tokens are provided,replace them with each other (ie,swap them). If optional second argument DELIMITED is nil,match words according to Syntax-table; otherwise match symbols. When called interactively,PLIST is input as space separated tokens,and DELIMITED as prefix arg." (interactive `(,(loop with input = (read-from-minibuffer "Replace: ") with limit = (length input) for j = 0 then i for (item . i) = (read-from-string input j) collect (prin1-to-string item t) until (<= limit i)),current-prefix-arg,(region-end))))) (let* ((alist (cond ((= (length plist) 2) (list plist (reverse plist))) ((loop for (key val . tail) on plist by #'cddr collect (list (prin1-to-string key t) val))))) (matcher (regexp-opt (mapcar #'car alist) (if delimited 'words 'symbols))) (to-spec `(replace-eval-replacement replace-quote (cadr (assoc-string (match-string 0) ',alist case-fold-search))))) (query-replace-regexp matcher to-spec nil start end)))