If I'm not mistaken, the solutions provided so far (using Perl and Vim) do not work properly if any of the replacements is among the last words to be replaced. In particular, none of the solutions work for the first example: "i" will be replaced by "in", which will then be incorrectly replaced by "ni", and then back to "i" by subsequent rules, while it should remain how in".
Substitutions cannot be considered independent and applied consistently; they must be applied in parallel.
In Emacs, you can do this:
Mx parallel-replace ,
and at the command prompt enter
i in in ni ni i .
Replacements will be made between the cursor and the end of the buffer or in the area, if selected.
(If you have this definition in ~/.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)))))))
Edit (2013-08-20):
Several improvements:
- For the special case, when only two elements are specified, exchange instead (i.e. replace each other);
- Request confirmation for each replacement in the same way as
query-replace .
(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 ,@(if (use-region-p) `(,(region-beginning) ,(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)))
huaiyuan
source share