首页 > 解决方案 > emacs:在区域上搜索和替换

问题描述

所以,我有这个出色的功能(有人为我制作的)用于在整个缓冲区上进行多次搜索和替换。

(defun accent-replace-whole-buffer ()
  "Corrects macrons from badly scanned latin"
  (interactive "*")
  (dolist (ele (list ?â ?ä ?ê ?ë ?î ?ô ?ü ?ï))
    (setq elt (char-to-string ele))
    (goto-char (point-min))
    (while (search-forward elt nil t 1)
      (replace-match
       (char-to-string
        (pcase ele
          (`?â ?ā)
          (`?ä ?ā)
          (`?ê ?ē)
          (`?ë ?ē)
          (`?î ?ī)
          (`?ô ?ō)     
          (`?ü ?ū)
          (`?ï ?ī)))))))

我想制作另一个功能,它只在选定的区域上执行此操作。

我该怎么办?哪里有不错的教程?

标签: searchemacsregion

解决方案


使用narrow-to-region,里面save-restriction

(defun accent-replace-in-region (begin end)
  "Corrects macrons in active region from badly scanned latin"
  (interactive "*r")
  (save-restriction
    (narrow-to-region begin end)
    (dolist (ele (list ?ā ?ā ?ē ?ē ?ī ?ō ?ū ?ī))
      (setq elt (char-to-string ele))
      (goto-char (point-min))
      (while (search-forward elt nil t 1)
        (replace-match
         (char-to-string
          (pcase ele
            (`?â ?ā)
            (`?ä ?ā)
            (`?ê ?ē)
            (`?ë ?ē)
            (`?î ?ī)
            (`?ô ?ō)     
            (`?ü ?ū)
            (`?ï ?ī))))))))

推荐阅读