在dired中查找并替换为无正则表达式
问题描述:
我试图将网站转换为电子书,并且在每个要删除的页面的开头都有一大块html。正如你可以想象的那样,使用Q
导致没有匹配,因为大块中的某些内容没有正确转义。当我尝试将问题解决时,我得到堆栈溢出。在dired中查找并替换为无正则表达式
我真正需要的是找到并替换而不使用正则表达式的方式,采用通常的M-%方式。这可能吗?
答
理论上,正则表达式的行为是可选的,但函数调用有问题的硬编码假设在一些地方。我认为最简单的解决方案是制作拷贝,它们在运行时不会设置正则表达式标志。
(eval-after-load 'dired
'(define-key dired-mode-map (kbd "C-c Q") 'my-dired-do-query-replace))
(defun my-dired-do-query-replace (from to &optional delimited)
"Do `query-replace' of FROM with TO, on all marked files.
Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
with the command \\[tags-loop-continue]."
(interactive
(let ((common
(query-replace-read-args
"Query replace in marked files" nil t)))
(list (nth 0 common) (nth 1 common) (nth 2 common))))
(require 'dired-aux)
(dolist (file (dired-get-marked-files nil nil 'dired-nondirectory-p))
(let ((buffer (get-file-buffer file)))
(if (and buffer (with-current-buffer buffer
buffer-read-only))
(error "File `%s' is visited read-only" file))))
(my-tags-query-replace
from to delimited '(dired-get-marked-files nil nil 'dired-nondirectory-p)))
(defun my-tags-query-replace (from to &optional delimited file-list-form)
"Do `query-replace' of FROM with TO on all files listed in tags table.
Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
with the command \\[tags-loop-continue].
Fourth arg FILE-LIST-FORM non-nil means initialize the replacement loop.
Fifth and sixth arguments START and END are accepted, for compatibility
with `query-replace', and ignored.
If FILE-LIST-FORM is non-nil, it is a form to evaluate to
produce the list of files to search.
See also the documentation of the variable `tags-file-name'."
(interactive (query-replace-read-args "Tags query replace" nil t))
(require 'etags)
(setq tags-loop-scan `(let ,(unless (equal from (downcase from))
'((case-fold-search nil)))
(if (search-forward ',from nil t)
;; When we find a match, move back
;; to the beginning of it so perform-replace
;; will see it.
(goto-char (match-beginning 0))))
tags-loop-operate `(perform-replace ',from ',to t nil ',delimited
nil multi-query-replace-map))
(tags-loop-continue (or file-list-form t)))
完美。只有抱怨(我很肯定会发生在正则表达式中)是当你按!它只完成当前缓冲区,而不是所有文件。仍然,2分钟的压制!对我来说是足够的解决方案! – 2013-02-24 23:37:02
是的,它实际上是原始函数的副本,只使用非正则表达式功能(和几个'require's,因为其他代码自动加载必要的库)进行了一些小修改。 – phils 2013-02-25 04:22:45