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

From: Juri Linkov <[email-masked]>
Date: Sat, 25 Dec 2021 21:04:58 +0200

> Could we improve 'repunctuate-sentences' to work such that in Transient
> Mark mode and with mark active, it re-punctuates the contents of the
> region?

Thanks for the request.  Until now, I used a custom command
'canonically-double-space-region' attached below, activated
by advice when the command 'fill-paragraph' (M-q) is called
on the region.

But its heuristics is too unreliable to detect the places
where two spaces are needed.  It often misidentifies
an abbreviation as the end of the sentence.  So using
'query-replace' would be more reliably to make the decision
for every punctuation.

When I tried 'repunctuate-sentences', it stunned by its inefficiency:
it requires a confirmation even when there are already two spaces
at the end of the sentence!  Why does it do this?

PS:

#+begin_src emacs-lisp
(defun canonically-double-space-region (beg end)
  (interactive "*r")
  (canonically-space-region beg end)
  (unless (markerp end) (setq end (copy-marker end t)))
  (let* ((sentence-end-double-space nil) ; to get right regexp below
         (end-spc-re (rx (>= 5 (not (in ".?!"))) (regexp (sentence-end)))))
    (save-excursion
      (goto-char beg)
      (while (and (< (point) end)
                  (re-search-forward end-spc-re end t))
        (unless (or (>= (point) end)
                    (looking-back "[[:space:]]\\{2\\}\\|\n" 3))
          (insert " "))))))

(advice-add 'fill-paragraph :before
            (lambda (&rest _args)
              (when (use-region-p)
                (canonically-double-space-region
                 (region-beginning)
                 (region-end))))
            '((name . fill-paragraph-double-space)))
#+end_src