Subject: bug#71017: fill-flowed-encode

From: Sandra Snan <[email-masked]>
Date: Fri, 17 May 2024 22:23:50 +0200

Hi y'all.

flow-fill.el.gz has a pair of functions, fill-flowed-encode and 
fill-flowed-fill-buffer (the latter is only called from the 
former).

Here is a fixed version of the former that then also deprecates 
the latter (I have signed FSF copyright papers):

(defun fill-flowed-encode (&optional buffer)
  (with-current-buffer (or buffer (current-buffer))
    ;; No point in doing this unless hard newlines is used.
    (when use-hard-newlines
      (let ((start (point-min)) end)
	;; Go through each paragraph, filling it and adding SPC
	;; as the last character on each line.
	(while (and (< start (point-max))
		    (setq end (or (text-property-any start (point-max) 'hard 't)
				  (point-max))))
	  (save-restriction
	    (narrow-to-region start end)
	    (let ((fill-column (eval fill-flowed-encode-column t))
		  (prefix
		   (concat "\n"
			   (or (and (looking-at ">[> ]*")
				    (match-string 0)) ""))))
	      (while (search-forward prefix nil t)
		(replace-match " " t t))
	      (goto-char start)
	      (while (< (+ (point) fill-column) (point-max))
		(forward-char fill-column)
		(search-backward " ")
		(forward-char)
		(insert prefix)))
	    (setq start (1+ (point-max))))))
      t)))

This fixes two bugs when sending RFC 2646–formatted email.

First, the old code didn't refill or encode the last paragraph at 
all unless there was at least one hard newline EOF.

Second, the old code borked up code indented with tabs and spaces 
(iff that code had overly long lines), such as the Lisp code in 
this email. It could sometimes insert extra in the middle of such 
long lines.

Here is an example of what it would do. It would turn this:

(defun lorem (ipsum)
  (dolor sit amet)
  (consectetur adipiscing elit (sed do eiusmod tempor incididunt 
ut labore et dolore magna aliqua))
  (ut enim ad minim veniam
      (quis nostrud exercitation ullamco laboris nisi ut aliquip 
ex ea commodo consequat
	    (duis aute irure dolor in reprehenderit in
		  voluptate velit esse cillum dolore
		  eu fugiat nulla pariatur)
	    excepteur sint occaecat cupidatat non proident
	    (sunt in culpa qui officia deserunt mollit anim id est 
laborumd))))

into this:

(defun lorem (ipsum)
  (dolor sit amet)
  (consectetur adipiscing elit (sed do eiusmod tempor incididunt
  ut labore et dolore magna aliqua))
  (ut enim ad minim veniam
      (quis nostrud exercitation ullamco laboris nisi ut aliquip
      ex ea commodo consequat
	    (duis aute irure dolor in reprehenderit in
		  voluptate velit esse cillum dolore
		  eu fugiat nulla pariatur)
	    excepteur sint occaecat cupidatat non proident
	    (sunt in culpa qui officia deserunt mollit anim id est
	    laborumd))))

It was breaking lines awkwardly so when they're reconnected they 
have extra whitespace in the mkddle of lines.