Fix Rmail editing with reapplying encoding to message body
[emacs.git] / lisp / mail / rmailedit.el
blobe9bb5560df8125b3a93bab0e06868200872b35f4
1 ;;; rmailedit.el --- "RMAIL edit mode" Edit the current message
3 ;; Copyright (C) 1985, 1994, 2001-2017 Free Software Foundation, Inc.
5 ;; Maintainer: emacs-devel@gnu.org
6 ;; Keywords: mail
7 ;; Package: rmail
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;;; Code:
28 (require 'rmail)
30 (defcustom rmail-edit-mode-hook nil
31 "List of functions to call when editing an RMAIL message."
32 :type 'hook
33 :version "21.1"
34 :group 'rmail-edit)
37 (defvar rmail-edit-map
38 (let ((map (make-sparse-keymap)))
39 ;; Make a keymap that inherits text-mode-map.
40 (set-keymap-parent map text-mode-map)
41 (define-key map "\C-c\C-c" 'rmail-cease-edit)
42 (define-key map "\C-c\C-]" 'rmail-abort-edit)
43 map))
45 (declare-function rmail-summary-disable "rmailsum" ())
47 ;; We can't straightforwardly make this derive from text-mode, because
48 ;; we need to bind (rmail-buffer-swapped) around the text-mode call. :(
49 (defun rmail-edit-mode ()
50 "Major mode for editing the contents of an Rmail message.
51 The editing commands are the same as in Text mode, together with
52 two commands to return to regular Rmail:
53 * \\[rmail-abort-edit] cancels any changes and returns to Rmail
54 * \\[rmail-cease-edit] makes them permanent.
55 This function runs the hooks `text-mode-hook' and `rmail-edit-mode-hook'.
56 \\{rmail-edit-map}"
57 (if (rmail-summary-exists)
58 (with-current-buffer rmail-summary-buffer
59 (rmail-summary-disable)))
60 ;; Prevent change-major-mode-hook from unswapping the buffers.
61 (let ((rmail-buffer-swapped nil))
62 (delay-mode-hooks (text-mode))
63 (use-local-map rmail-edit-map)
64 (setq major-mode 'rmail-edit-mode)
65 (setq mode-name "RMAIL Edit")
66 (if (boundp 'mode-line-modified)
67 (setq mode-line-modified (default-value 'mode-line-modified))
68 (setq mode-line-format (default-value 'mode-line-format)))
69 ;; Don't turn off auto-saving based on the size of the buffer
70 ;; because that code does not understand buffer-swapping.
71 (make-local-variable 'auto-save-include-big-deletions)
72 (setq auto-save-include-big-deletions t)
73 ;; If someone uses C-x C-s, don't clobber the rmail file (bug#2625).
74 (add-hook 'write-region-annotate-functions
75 'rmail-write-region-annotate nil t)
76 (run-mode-hooks 'rmail-edit-mode-hook)))
78 ;; Rmail Edit mode is suitable only for specially formatted data.
79 (put 'rmail-edit-mode 'mode-class 'special)
82 (defvar rmail-old-text)
83 (defvar rmail-old-mime-state)
84 (defvar rmail-old-pruned nil
85 "Non-nil means the message being edited originally had pruned headers.")
86 (put 'rmail-old-pruned 'permanent-local t)
88 (defvar rmail-old-headers nil
89 "Holds the headers of this message before editing started.")
90 (put 'rmail-old-headers 'permanent-local t)
92 ;; Everything we use from here is a defsubst.
93 (eval-when-compile
94 (require 'rmailmm))
96 ;;;###autoload
97 (defun rmail-edit-current-message ()
98 "Edit the contents of this message."
99 (interactive)
100 (if (zerop rmail-total-messages)
101 (error "No messages in this buffer"))
102 (rmail-modify-format)
103 (make-local-variable 'rmail-old-pruned)
104 (setq rmail-old-pruned (rmail-msg-is-pruned))
105 (rmail-edit-mode)
106 (set (make-local-variable 'rmail-old-mime-state)
107 (and rmail-enable-mime
108 ;; If you use something else, you are on your own.
109 (eq rmail-mime-feature 'rmailmm)
110 (rmail-mime-message-p)
111 (let ((entity (get-text-property (point-min) 'rmail-mime-entity)))
112 ;; rmailmm has got its hands on the message.
113 ;; Even if the message is in `raw' state, boundaries etc
114 ;; are still missing. All we can do is insert the real
115 ;; raw message. (Bug#9840)
116 ;; FIXME? Since the 2012-09-17 changes to rmail-mime,
117 ;; can we just use that function now?
118 (when (and entity
119 (not (equal "text/plain"
120 (car (rmail-mime-entity-type entity)))))
121 (let ((inhibit-read-only t))
122 (erase-buffer)
123 (insert-buffer-substring
124 rmail-view-buffer
125 (aref (rmail-mime-entity-header entity) 0)
126 (aref (rmail-mime-entity-body entity) 1)))
127 (goto-char (point-min))
128 ;; t = decoded; raw = raw.
129 (aref (aref (rmail-mime-entity-display entity) 0) 0)))))
130 (make-local-variable 'rmail-old-text)
131 (setq rmail-old-text
132 (save-restriction
133 (widen)
134 (buffer-substring (point-min) (point-max))))
135 (make-local-variable 'rmail-old-headers)
136 (setq rmail-old-headers (rmail-edit-headers-alist t))
137 (setq buffer-read-only nil)
138 (setq buffer-undo-list nil)
139 ;; Whether the buffer is initially marked as modified or not
140 ;; depends on whether or not the underlying rmail buffer was so marked.
141 ;; Given the way this works, it has to.
142 ;; If you kill the edit buffer, you've killed your rmail buffer.
143 (force-mode-line-update)
144 (if (and (eq (key-binding "\C-c\C-c") 'rmail-cease-edit)
145 (eq (key-binding "\C-c\C-]") 'rmail-abort-edit))
146 (message "Editing: Type C-c C-c to return to Rmail, C-c C-] to abort")
147 (message "%s" (substitute-command-keys
148 "Editing: Type \\[rmail-cease-edit] to return to Rmail, \\[rmail-abort-edit] to abort"))))
151 (declare-function rmail-summary-enable "rmailsum" ())
153 (defun rmail-cease-edit ()
154 "Finish editing message; switch back to Rmail proper."
155 (interactive)
156 (if (rmail-summary-exists)
157 (with-current-buffer rmail-summary-buffer
158 (rmail-summary-enable)))
159 (widen)
160 (goto-char (point-min))
161 ;; This is far from ideal. The edit may have inadvertently
162 ;; removed the blank line at the end of the headers, but there
163 ;; are almost certainly other blank lines.
164 (or (search-forward "\n\n" nil t)
165 (error "There must be a blank line at the end of the headers"))
166 ;; Disguise any "From " lines so they don't start a new message.
167 (goto-char (point-min))
168 ;; This tries to skip the mbox From. FIXME less fragile to go to EOH?
169 (if (or rmail-old-mime-state
170 (not rmail-old-pruned))
171 (forward-line 1))
172 ;; When editing a non-MIME message, rmail-show-message-1 has unescaped
173 ;; ^>*From lines according to rmail-mbox-format. We are editing
174 ;; the message as it was displayed, and need to put the escapes when done.
175 ;; When editing a MIME message, we are editing the "raw" message.
176 ;; ^>*From lines have not been escaped, but we still need to ensure
177 ;; a "^From " line is escaped so as not to break later parsing (?).
178 ;; With ^>+From lines, we have no way of knowing whether the person
179 ;; doing the editing escaped them or not, so it seems best to leave
180 ;; them alone. (This all assumes you are using rmailmm rather than
181 ;; something else that behaves differently.)
182 (let ((fromline (if (or (eq 'mboxo rmail-mbox-format)
183 rmail-mime-decoded)
184 "^From "
185 "^>*From "))
186 case-fold-search)
187 (while (re-search-forward fromline nil t)
188 (beginning-of-line)
189 (insert ">")
190 (forward-line)))
191 (let ((old rmail-old-text)
192 (pruned rmail-old-pruned)
193 (mime-state rmail-old-mime-state)
194 ;; People who know what they are doing might have modified the
195 ;; buffer's encoding if editing the message included inserting
196 ;; characters that were unencodable by the original message's
197 ;; encoding. Make note of the new encoding and use it for
198 ;; encoding the edited message.
199 (edited-coding buffer-file-coding-system)
200 new-headers
201 character-coding is-text-message coding-system
202 headers-end limit)
203 ;; Make sure `edited-coding' can safely encode the edited message.
204 (setq edited-coding
205 (select-safe-coding-system (point-min) (point-max) edited-coding))
206 ;; Go back to Rmail mode, but carefully.
207 (force-mode-line-update)
208 (let ((rmail-buffer-swapped nil)) ; Prevent change-major-mode-hook
209 ; from unswapping the buffers.
210 (kill-all-local-variables)
211 (rmail-mode-1)
212 (if (boundp 'tool-bar-map)
213 (set (make-local-variable 'tool-bar-map) rmail-tool-bar-map))
214 (setq buffer-undo-list t)
215 (rmail-variables))
216 ;; If text has really changed, mark message as edited.
217 ;; FIXME we should do the comparison before escaping From lines.
218 (unless (and (= (length old) (- (point-max) (point-min)))
219 (string= old (buffer-substring (point-min) (point-max))))
220 (setq old nil)
221 (goto-char (point-min))
222 (search-forward "\n\n")
223 (setq headers-end (point-marker)) ; first character of body
224 (save-restriction
225 (narrow-to-region (point-min) headers-end)
226 ;; If they changed the message's encoding, rewrite the charset=
227 ;; header for them, so that subsequent rmail-show-message
228 ;; decodes it correctly.
229 (let* ((buffer-read-only nil)
230 (new-coding (coding-system-base edited-coding))
231 (mime-charset (symbol-name
232 (or (coding-system-get new-coding :mime-charset)
233 (if (coding-system-equal new-coding
234 'undecided)
235 'us-ascii
236 new-coding))))
237 old-coding mime-beg mime-end content-type)
238 ;; If there's no content-type in the edited headers, look for one
239 ;; in the original headers and add it to the edited headers
240 ;; (Bug #26918)
241 (unless (mail-fetch-field "Content-Type")
242 (let (old-content-type
243 (msgbeg (rmail-msgbeg rmail-current-message))
244 (msgend (rmail-msgend rmail-current-message)))
245 (with-current-buffer rmail-view-buffer ; really the mbox buffer
246 (save-restriction
247 (narrow-to-region msgbeg msgend)
248 (goto-char (point-min))
249 (setq limit (search-forward "\n\n"))
250 (narrow-to-region (point-min) limit)
251 (goto-char (point-min))
252 (when (re-search-forward "^content-type:" limit t)
253 (forward-line)
254 (setq old-content-type (buffer-substring
255 (match-beginning 0) (point))))))
256 (when old-content-type
257 (save-excursion
258 (goto-char headers-end) ; first char of body
259 (backward-char) ; add header before second newline
260 (insert old-content-type)
261 ;;Add it to rmail-old-headers as though it had been
262 ;;there originally, to avoid rmail-edit-update-headers
263 ;;an extra copy
264 (let ((header (substring old-content-type 0
265 (length "content-type"))))
266 (unless (assoc header rmail-old-headers)
267 (push (cons header old-content-type) rmail-old-headers)))
268 ))))
269 (goto-char (point-min))
270 (if (re-search-forward rmail-mime-charset-pattern nil 'move)
271 (setq mime-beg (match-beginning 1)
272 mime-end (match-end 1)
273 old-coding (coding-system-from-name (match-string 1)))
274 (setq content-type (mail-fetch-field "Content-Type")))
275 (cond
276 ;; No match for rmail-mime-charset-pattern, but there was some
277 ;; other Content-Type. We should not insert another. (Bug#4624)
278 (content-type)
279 ((null old-coding)
280 ;; If there was no charset= spec, insert one.
281 (backward-char 1)
282 (insert "Content-type: text/plain; charset=" mime-charset "\n"))
283 ((not (coding-system-equal (coding-system-base old-coding)
284 new-coding))
285 (goto-char mime-end)
286 (delete-region mime-beg mime-end)
287 (insert mime-charset)))))
288 (setq new-headers (rmail-edit-headers-alist t))
289 (rmail-swap-buffers-maybe)
290 (narrow-to-region (rmail-msgbeg rmail-current-message)
291 (rmail-msgend rmail-current-message))
292 (goto-char (point-min))
293 (setq limit (search-forward "\n\n"))
294 (save-restriction
295 ;; All 3 of the functions we call below assume the buffer was
296 ;; narrowed to just the headers of the message.
297 (narrow-to-region (point-min) limit)
298 (setq character-coding
299 (mail-fetch-field "content-transfer-encoding")
300 is-text-message (rmail-is-text-p)
301 coding-system (if (and edited-coding
302 (not (coding-system-equal
303 (coding-system-base edited-coding)
304 'undecided)))
305 edited-coding
306 (rmail-get-coding-system))))
307 (if character-coding
308 (setq character-coding (downcase character-coding)))
310 (goto-char limit)
311 (let ((inhibit-read-only t)
312 (data-buffer (current-buffer))
313 (start (copy-marker (point) nil)) ; new body will be between
314 (end (copy-marker (point) t))) ; these two markers
315 (with-current-buffer rmail-view-buffer
316 (encode-coding-region headers-end (point-max) coding-system
317 data-buffer))
318 (delete-region end (point-max))
319 ;; Apply to the mbox buffer any changes in header fields
320 ;; that the user made while editing in the view buffer.
321 (rmail-edit-update-headers (rmail-edit-diff-headers
322 rmail-old-headers new-headers))
323 ;; Re-apply content-transfer-encoding, if any, on the message body.
324 (cond
325 ((string= character-coding "quoted-printable")
326 (mail-quote-printable-region start (point-max)))
327 ((and (string= character-coding "base64") is-text-message)
328 (base64-encode-region start (point-max)))
329 ((and (eq character-coding 'uuencode) is-text-message)
330 (error "uuencoded messages are not supported")))
331 ;; After encoding, make sure buffer ends with a blank line so as not to
332 ;; run this message together with the following one.
333 (goto-char (point-max))
334 (rmail-ensure-blank-line))
335 (rmail-set-attribute rmail-edited-attr-index t))
336 ;;;??? BROKEN perhaps.
337 ;;; (if (boundp 'rmail-summary-vector)
338 ;;; (aset rmail-summary-vector (1- rmail-current-message) nil))
339 (rmail-show-message)
340 (rmail-toggle-header (if pruned 1 0))
341 ;; Restore mime display state.
342 (and mime-state (rmail-mime nil mime-state)))
343 (run-hooks 'rmail-mode-hook))
345 (defun rmail-abort-edit ()
346 "Abort edit of current message; restore original contents."
347 (interactive)
348 (widen)
349 (delete-region (point-min) (point-max))
350 (insert rmail-old-text)
351 (rmail-cease-edit)
352 (rmail-highlight-headers))
354 (defun rmail-edit-headers-alist (&optional widen markers)
355 "Return an alist of the headers of the message in the current buffer.
356 Each element has the form (HEADER-NAME . ENTIRE-STRING).
357 ENTIRE-STRING includes the name of the header field (which is HEADER-NAME)
358 and has a final newline.
359 If part of the text is not valid as a header field, HEADER-NAME
360 is an integer and we use consecutive integers.
362 If WIDEN is non-nil, operate on the entire buffer.
364 If MARKERS is non-nil, the value looks like
365 \(HEADER-NAME ENTIRE-STRING BEG-MARKER END-MARKER)."
366 (let (header-alist (no-good-header-count 1))
367 (save-excursion
368 (save-restriction
369 (if widen (widen))
370 (goto-char (point-min))
371 (search-forward "\n\n")
372 (narrow-to-region (point-min) (1- (point)))
373 (goto-char (point-min))
374 (while (not (eobp))
375 (let ((start (point))
376 name header)
377 ;; Match the name.
378 (if (looking-at "[ \t]*\\([^:\n \t]\\(\\|[^:\n]*[^:\n \t]\\)\\)[ \t]*:")
379 (setq name (match-string-no-properties 1))
380 (setq name no-good-header-count
381 no-good-header-count (1+ no-good-header-count)))
382 (forward-line 1)
383 (while (looking-at "[ \t]")
384 (forward-line 1))
385 (setq header (buffer-substring-no-properties start (point)))
386 (if markers
387 (push (list header (copy-marker start) (point-marker))
388 header-alist)
389 (push (cons name header) header-alist))))))
390 (nreverse header-alist)))
393 (defun rmail-edit-diff-headers (old-headers new-headers)
394 "Compare OLD-HEADERS and NEW-HEADERS and return field differences.
395 The value is a list of three lists, (INSERTED DELETED CHANGED).
397 INSERTED's elements describe inserted header fields
398 and each looks like (AFTER-WHAT INSERT-WHAT)
399 INSERT-WHAT is the header field to insert (a member of NEW-HEADERS).
400 AFTER-WHAT is the field to insert it after (a member of NEW-HEADERS)
401 or else nil to insert it at the beginning.
403 DELETED's elements are elements of OLD-HEADERS.
404 CHANGED's elements have the form (OLD . NEW)
405 where OLD is a element of OLD-HEADERS and NEW is an element of NEW-HEADERS."
407 (let ((reverse-new (reverse new-headers))
408 inserted deleted changed)
409 (dolist (old old-headers)
410 (let ((new (assoc (car old) new-headers)))
411 ;; If it's in OLD-HEADERS and has no new counterpart,
412 ;; it is a deletion.
413 (if (null new)
414 (push old deleted)
415 ;; If it has a new counterpart, maybe it was changed.
416 (unless (equal (cdr old) (cdr new))
417 (push (cons old new) changed))
418 ;; Remove the new counterpart, since it has been spoken for.
419 (setq new-headers (remq new new-headers)))))
420 ;; Look at the new headers with no old counterpart.
421 (dolist (new new-headers)
422 (let ((prev (cadr (member new reverse-new))))
423 ;; Mark each one as an insertion.
424 ;; Record the previous new header, to insert it after that.
425 (push (list prev new) inserted)))
426 ;; It is crucial to return the insertions in buffer order
427 ;; so that `rmail-edit-update-headers' can insert a field
428 ;; after a new field.
429 (list (nreverse inserted)
430 (nreverse deleted)
431 (nreverse changed))))
433 (defun rmail-edit-update-headers (header-diff)
434 "Edit the mail headers in the buffer based on HEADER-DIFF.
435 HEADER-DIFF should be a return value from `rmail-edit-diff-headers'."
436 (let ((buf-headers (rmail-edit-headers-alist nil t)))
437 ;; Change all the fields scheduled for being changed.
438 (dolist (chg (nth 2 header-diff))
439 (let* ((match (assoc (cdar chg) buf-headers))
440 (end (marker-position (nth 2 match))))
441 (goto-char end)
442 ;; Insert the new, then delete the old.
443 ;; That avoids collapsing markers.
444 (insert-before-markers (cddr chg))
445 (delete-region (nth 1 match) end)
446 ;; Remove the old field from BUF-HEADERS.
447 (setq buf-headers (delq match buf-headers))
448 ;; Update BUF-HEADERS to show the changed field.
449 (push (list (cddr chg) (point-marker)
450 (copy-marker (- (point) (length (cddr chg))))
451 (point-marker))
452 buf-headers)))
453 ;; Delete all the fields scheduled for deletion.
454 ;; We do deletion after changes
455 ;; because when two fields look alike and get replaced by one,
456 ;; the first of them is considered changed
457 ;; and the second is considered deleted.
458 (dolist (del (nth 1 header-diff))
459 (let ((match (assoc (cdr del) buf-headers)))
460 (delete-region (nth 1 match) (nth 2 match))))
461 ;; Insert all the fields scheduled for insertion.
462 (dolist (ins (nth 0 header-diff))
463 (let* ((new (cadr ins))
464 (after (car ins))
465 (match (assoc (cdr after) buf-headers)))
466 (goto-char (if match (nth 2 match) (point-min)))
467 (insert (cdr new))
468 ;; Update BUF-HEADERS to show the inserted field.
469 (push (list (cdr new)
470 (copy-marker (- (point) (length (cdr new))))
471 (point-marker))
472 buf-headers)))
473 ;; Disconnect the markers
474 (dolist (hdr buf-headers)
475 (set-marker (nth 1 hdr) nil)
476 (set-marker (nth 2 hdr) nil))))
478 (provide 'rmailedit)
480 ;; Local Variables:
481 ;; generated-autoload-file: "rmail-loaddefs.el"
482 ;; End:
484 ;;; rmailedit.el ends here