簡體   English   中英

交互式Emacs Lisp函數可以互相交換兩個單詞

[英]Interactive Emacs Lisp function to swap two words with each other

我第一次進入emacs lisp的古怪世界是一個函數,它需要兩個字符串並互相交換它們:

(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工作)
  • 如何轉義字符串ab ,如果它們包含任何正則表達式字符,它們不會被解釋為正則表達式?

編輯:我用了一段時間的最終拷貝可用代碼是:

(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那樣突出顯示頁面上即將到來的匹配。

使用y-or-np作為第一個:( (when (y-or-np "Swap?") do stuff

regexp-quote第二個:( (regexp-quote your-string)

regexp-quote 已經提到了

至於確認,如果您想在每次替換之前詢問用戶,您可以選擇完全符合您要求的query-replace-regexp

(你仍然可以處理Emacs的內置轉發函數 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM