2012-12-04 40 views
5

這與 Emacs: regular expression replacing to change caseEmacs的:正則表達式替換改變的情況下(腳本)

我的另外一個問題是,我需要劇本搜索替換,但使用僅在"\,()"解決方案的工作(對我來說)交互式地(emacs 24.2.1)。在腳本內部會出現錯誤:「替換文字中使用\'無效」。

我通常會在需要時寫入一個「執行替換」到某個文件來加載。喜歡的東西:

(執行替換"<\\([^>]+\\)>" "<\\,(downcase \1)>" TT零1零(點分)(點-MAX))

應該可以調用一個函數來產生替代(pg 741 of the emacs lisp manual),但我試過很多沒有運氣的下列變化:

(defun myfun() 
    (downcase (match-string 0))) 

(perform-replace "..." (myfun .()) t t nil) 

任何人都可以幫忙嗎?

回答

3

\,()這樣的結構只允許在query-replace互動電話,這就是爲什麼Emacs在你的情況下抱怨。

perform-replace說明文檔中提到,你不應該在elisp的代碼中使用它,並提出了一個更好的選擇,在其中我們可以建立下面的代碼:

(while (re-search-forward "<\\([^>]+\\)>" nil t) 
    (replace-match (downcase (match-string 0)) t nil)) 

如果您仍想以交互方式查詢關於替換的用戶,使用perform-replace就像你做的可能是正確的做法。有在你的代碼的幾個不同的問題:

  1. 正如elisp manual規定的替換功能必須採取兩個參數(已讓你在cons單元提供數據和更換的數量)。

  2. 作爲query-replace-regexp的文檔(或elisp manual)中所述,需要確保case-fold-searchcase-replace被設置爲零,使得殼體圖案不轉移到替換。

  3. 您需要引用cons cell (myfun . nil),否則將被解釋爲函數調用並且評估得太早。

這裏是一個工作版本:

(let ((case-fold-search nil)) 
    (perform-replace "<\\([^>]+\\)>" 
        `(,(lambda (data count) 
         (downcase (match-string 0)))) 
        t t nil)) 
+0

nop,我需要查詢(y/n /!等),並突出執行替換的能力(我不希望重新實現它用y或np + highlight-regexp或類似的) –

+0

你可能想要編輯你的問題來反映這個約束。無論如何,我提出了一個基於'perform-replace'的解決方案,它可以滿足您的要求。 – Francesco

2

C-h f perform-replace說:

Don't use this in your own program unless you want to query and set the mark 
just as `query-replace' does. Instead, write a simple loop like this: 

    (while (re-search-forward "foo[ \t]+bar" nil t) 
    (replace-match "foobar")) 

現在"<\\,(downcase \1)>"需要通過建立正確的琴絃的elisp的表達式來代替,如(format "<%s>" (downcase (match-string 1)))

如果您確實需要查詢和內容,那麼您可能想嘗試:C-M-% f\(o\)o RET bar \,(downcase \1) baz RET然後C-x RET RET以查看在交互式調用期間構建了哪些參數。

你會看到發現(甚至更好,如果你在C-h f perform-replace點擊replace.el看到函數的源代碼),該replacements參數可以採取的形式(FUNCTION。參數)。更具體地說,代碼包括一個評論給出的一些細節:

;; REPLACEMENTS is either a string, a list of strings, or a cons cell 
;; containing a function and its first argument. The function is 
;; called to generate each replacement like this: 
;; (funcall (car replacements) (cdr replacements) replace-count) 
;; It must return a string. 
;; REPLACEMENTS is either a string, a list of strings, or a cons cell 
;; containing a function and its first argument. The function is 
;; called to generate each replacement like this: 
;; (funcall (car replacements) (cdr replacements) replace-count) 
;; It must return a string. 
+0

我確實需要「查詢」:-) –