5

emacs lisp の風変わりな世界への私の最初の進出は、2 つの文字列を取り、それらを互いに交換する関数です。

(defun swap-strings (a b)
  "Replace all occurances of a with b and vice versa"
  (interactive "*sFirst Swap Word: \nsSecond Swap Word: ")
  (save-excursion
    (while (re-search-forward (concat a "\\|" b) nil t)
      (if (equal (match-string 0) a)
      (replace-match b)
    (replace-match a)))))

これは機能しますが、次のことにこだわっています。

  • 各交換の前にユーザーに確認を促す方法は? (仕事に行けないperform-replace)
  • a文字列をエスケープしてb、正規表現文字が含まれている場合に正規表現として解釈されないようにする方法は?

編集:私がしばらく使用してきた最終的なコピーペースト可能なコードは次のとおりです。

(defun swap-words (a b)
  "Replace all occurances of a with b and vice versa"
  (interactive "*sFirst Swap Word: \nsSecond Swap Word: ")
  (save-excursion
    (while (re-search-forward (concat (regexp-quote a) "\\|" (regexp-quote b)))
      (if (y-or-n-p "Swap?") 
      (if (equal (match-string 0) a)
          (replace-match (regexp-quote b))
        (replace-match (regexp-quote a))))
      )))

残念ながら、I-search のように、ページ上で次の一致をハイライト表示しません。

4

2 に答える 2

1

regexp-quote既出です。

確認に関しては、各交換の前にユーザーに尋ねたい場合は、query-replace-regexpまさにあなたが望むものを選択することができます。

(そして、Emacs の組み込みトランスポンス関数を扱うこともできます。)

于 2009-04-20T14:42:30.580 に答える