Subject: Re: bug#52769: 29.0.50; [FEATURE REQUEST] repunctuate-sentences in region

From: Juri Linkov <[email-masked]>
Date: Tue, 28 Dec 2021 22:18:12 +0200

> If no one has a better idea for a simpler implementation,
> then this patch fixes the problem by skipping the sentences
> that already have two spaces at the end:

The filter will also allow redefining it with own logic
such as skipping known abbreviations that don't require
two spaces, i.e., e.g.:

  (defun repunctuate-sentences-filter (_start _end)
    (not (or (length= (match-string 4) 2)
             (looking-back (rx (or "i.e." "e.g.") " ") 5))))

diff --git a/lisp/textmodes/paragraphs.el b/lisp/textmodes/paragraphs.el
index acb26fd1c1..580f3617d0 100644
--- a/lisp/textmodes/paragraphs.el
+++ b/lisp/textmodes/paragraphs.el
@@ -479,6 +479,9 @@ forward-sentence
       (setq arg (1- arg)))
     (constrain-to-field nil opoint t)))
 
+(defun repunctuate-sentences-filter (_start _end)
+  (not (length= (match-string 4) 2)))
+
 (defun repunctuate-sentences (&optional no-query start end)
   "Put two spaces at the end of sentences from point to the end of buffer.
 It works using `query-replace-regexp'.  In Transient Mark mode,
@@ -489,14 +492,21 @@ repunctuate-sentences
   (interactive (list nil
                      (if (use-region-p) (region-beginning))
                      (if (use-region-p) (region-end))))
-  (let ((regexp "\\([]\"')]?\\)\\([.?!]\\)\\([]\"')]?\\) +")
-        (to-string "\\1\\2\\3  "))
-    (if no-query
-        (progn
-          (when start (goto-char start))
-          (while (re-search-forward regexp end t)
-            (replace-match to-string)))
-      (query-replace-regexp regexp to-string nil start end))))
+  (if no-query
+      (let ((regexp "\\([]\"')]?\\)\\([.?!]\\)\\([]\"')]?\\) +")
+            (to-string "\\1\\2\\3  "))
+        (when start (goto-char start))
+        (while (re-search-forward regexp end t)
+          (replace-match to-string)))
+    (let ((regexp "\\([]\"')]?\\)\\([.?!]\\)\\([]\"')]?\\)\\( +\\)")
+          (to-string "\\1\\2\\3  "))
+      (unwind-protect
+          (progn
+            (add-function :after-while isearch-filter-predicate
+                          #'repunctuate-sentences-filter)
+            (query-replace-regexp regexp to-string nil start end))
+        (remove-function isearch-filter-predicate
+                         #'repunctuate-sentences-filter)))))

 (defun backward-sentence (&optional arg)