[英]emacs: search and replace on a region
So, I have this excellent function (that someone made for me) for doing multiple search and replaces on an entire buffer.所以,我有这个出色的 function(有人为我制作)用于在整个缓冲区上进行多次搜索和替换。
(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
(`?â ?ā)
(`?ä ?ā)
(`?ê ?ē)
(`?ë ?ē)
(`?î ?ī)
(`?ô ?ō)
(`?ü ?ū)
(`?ï ?ī)))))))
and I would like to make another function, which does this, only on the selected region.我想制作另一个 function,它只在选定的区域上执行此操作。
How would I go about this?我将如何 go 关于这个? Is there a nice tutorial anywhere?哪里有不错的教程?
Use narrow-to-region
, inside save-restriction
:在save-restriction
内使用narrow-to-region
:
(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
(`?â ?ā)
(`?ä ?ā)
(`?ê ?ē)
(`?ë ?ē)
(`?î ?ī)
(`?ô ?ō)
(`?ü ?ū)
(`?ï ?ī))))))))
Instead of the builtin interactive code "r", using that form:而不是内置的交互式代码“r”,使用这种形式:
(defun MYFUNTION (&optional beg end)
(interactive "*")
(let ((beg (cond (beg)
((use-region-p)
(region-beginning))
(t (point-min))))
(end (cond (end (point-marker end))
((use-region-p)
(point-marker (region-end)))
(t (point-marker (point-max))))))
(and beg end (narrow-to-region beg end))
(goto-char beg)
;; here some replace example revealing the problem mentioned
(while (re-search-forward "." end t 1)
(replace-match "+++++++++"))))
Basically two reasons for this: Make sure, the region is visible when acting upon - "r" doesn't care for transient-mark-mode etc. Unfortunatly use-region-p
also has some quirks, but better than no reliabilty at all.基本上有两个原因:确保该区域在作用时可见 - “r”不关心瞬态标记模式等。不幸use-region-p
也有一些怪癖,但总比没有可靠性好. Second reason: end
needs to be updated when a replacing will change the length of the region.第二个原因:当替换会改变区域的长度时,需要更新end
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.