1;;; rmailmm.el --- MIME decoding and display stuff for RMAIL
2
3;; Copyright (C) 2006-2021 Free Software Foundation, Inc.
4
5;; Author: Alexander Pohoyda
6;;	Alex Schroeder
7;; Maintainer: emacs-devel@gnu.org
8;; Keywords: mail
9;; Package: rmail
10
11;; This file is part of GNU Emacs.
12
13;; GNU Emacs is free software: you can redistribute it and/or modify
14;; it under the terms of the GNU General Public License as published by
15;; the Free Software Foundation, either version 3 of the License, or
16;; (at your option) any later version.
17
18;; GNU Emacs is distributed in the hope that it will be useful,
19;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21;; GNU General Public License for more details.
22
23;; You should have received a copy of the GNU General Public License
24;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
25
26;;; Commentary:
27
28;; Essentially based on the design of Alexander Pohoyda's MIME
29;; extensions (mime-display.el and mime.el).
30
31;; This file provides two operation modes for viewing a MIME message.
32
33;; (1) When rmail-enable-mime is non-nil (now it is the default), the
34;; function `rmail-show-mime' is automatically called.  That function
35;; shows a MIME message directly in RMAIL's view buffer.
36
37;; (2) When rmail-enable-mime is nil, the command 'v' (or M-x
38;; rmail-mime) shows a MIME message in a new buffer "*RMAIL*".
39
40;; Both operations share the intermediate functions rmail-mime-process
41;; and rmail-mime-process-multipart as below.
42
43;; rmail-show-mime
44;;   +- rmail-mime-parse
45;;   |    +- rmail-mime-process <--+------------+
46;;   |         |         +---------+            |
47;;   |         + rmail-mime-process-multipart --+
48;;   |
49;;   + rmail-mime-insert <----------------+
50;;       +- rmail-mime-insert-text        |
51;;       +- rmail-mime-insert-bulk        |
52;;       +- rmail-mime-insert-multipart --+
53;;
54;; rmail-mime
55;;  +- rmail-mime-show <----------------------------------+
56;;       +- rmail-mime-process                            |
57;;            +- rmail-mime-handle                        |
58;;                 +- rmail-mime-text-handler             |
59;;                 +- rmail-mime-bulk-handler             |
60;;                 |    + rmail-mime-insert-bulk
61;;                 +- rmail-mime-multipart-handler        |
62;;                      +- rmail-mime-process-multipart --+
63
64;; In addition, for the case of rmail-enable-mime being non-nil, this
65;; file provides two functions rmail-insert-mime-forwarded-message and
66;; rmail-insert-mime-resent-message for composing forwarded and resent
67;; messages respectively.
68
69;; Todo:
70
71;; Make rmail-mime-media-type-handlers-alist usable in the first
72;; operation mode.
73;; Handle multipart/alternative in the second operation mode.
74;; Offer the option to call external/internal viewers (doc-view, xpdf, etc).
75
76;;; Code:
77
78(require 'rmail)
79(require 'mail-parse)
80(require 'message)
81
82;;; User options.
83
84(defgroup rmail-mime nil
85  "Rmail MIME handling options."
86  :prefix "rmail-mime-"
87  :group 'rmail)
88
89(defcustom rmail-mime-media-type-handlers-alist
90  '(("multipart/.*" rmail-mime-multipart-handler)
91    ("text/.*" rmail-mime-text-handler)
92    ("text/\\(x-\\)?patch" rmail-mime-bulk-handler)
93    ("\\(image\\|audio\\|video\\|application\\)/.*" rmail-mime-bulk-handler))
94  "Functions to handle various content types.
95This is an alist with elements of the form (REGEXP FUNCTION ...).
96The first item is a regular expression matching a content-type.
97The remaining elements are handler functions to run, in order of
98decreasing preference.  These are called until one returns non-nil.
99Note that this only applies to items with an inline Content-Disposition,
100all others are handled by `rmail-mime-bulk-handler'.
101Note also that this alist is ignored when the variable
102`rmail-enable-mime' is non-nil."
103  :type '(alist :key-type regexp :value-type (repeat function))
104  :version "23.1"
105  :group 'rmail-mime)
106
107(defcustom rmail-mime-attachment-dirs-alist
108  `(("text/.*" "~/Documents")
109    ("image/.*" "~/Pictures")
110    (".*" "~/Desktop" "~" ,temporary-file-directory))
111  "Default directories to save attachments of various types into.
112This is an alist with elements of the form (REGEXP DIR ...).
113The first item is a regular expression matching a content-type.
114The remaining elements are directories, in order of decreasing preference.
115The first directory that exists is used."
116  :type '(alist :key-type regexp :value-type (repeat directory))
117  :version "23.1"
118  :group 'rmail-mime)
119
120(defcustom rmail-mime-show-images 'button
121  "What to do with image attachments that Emacs is capable of displaying.
122If nil, do nothing special.  If `button', add an extra button
123that when pushed displays the image in the buffer.  If a number,
124automatically show images if they are smaller than that size (in
125bytes), otherwise add a display button.  Anything else means to
126automatically display the image in the buffer."
127  :type '(choice (const :tag "Add button to view image" button)
128		 (const :tag "No special treatment" nil)
129		 (number :tag "Show if smaller than certain size")
130		 (other :tag "Always show" show))
131  :version "23.2"
132  :group 'rmail-mime)
133
134(defcustom rmail-mime-render-html-function
135  (cond ((fboundp 'libxml-parse-html-region) 'rmail-mime-render-html-shr)
136	((executable-find "lynx") 'rmail-mime-render-html-lynx)
137	(t nil))
138  "Function to convert HTML to text.
139Called with buffer containing HTML extracted from message in a
140temporary buffer.  Converts to text in current buffer.  If nil,
141display HTML source."
142  :group 'rmail
143  :version "25.1"
144  :type '(choice function (const nil)))
145
146(defcustom rmail-mime-prefer-html
147  ;; Default to preferring HTML parts, but only if we have a renderer
148  (if rmail-mime-render-html-function t nil)
149  "If non-nil, default to showing HTML part rather than text part
150when both are available."
151  :group 'rmail
152  :version "25.1"
153  :type 'boolean)
154
155;;; End of user options.
156
157;;; Global variables that always have let-binding when referred.
158
159(defvar rmail-mime-mbox-buffer nil
160  "Buffer containing the mbox data.
161The value is usually nil, and bound to a proper value while
162processing MIME.")
163
164(defvar rmail-mime-view-buffer nil
165  "Buffer showing a message.
166The value is usually nil, and bound to a proper value while
167processing MIME.")
168
169(defvar rmail-mime-coding-system nil
170  "The first coding-system used for decoding a MIME entity.
171The value is usually nil, and bound to non-nil while inserting
172MIME entities.")
173
174(defvar rmail-mime-searching nil
175  "Bound to T inside `rmail-search-mime-message' to suppress expensive
176operations such as HTML decoding")
177
178;;; MIME-entity object
179
180(defun rmail-mime-entity (type disposition transfer-encoding
181			       display header tagline body children handler
182			       &optional truncated)
183  "Return a newly created MIME-entity object from arguments.
184
185A MIME-entity is a vector of 10 elements:
186
187  [TYPE DISPOSITION TRANSFER-ENCODING DISPLAY HEADER TAGLINE BODY
188   CHILDREN HANDLER TRUNCATED]
189
190TYPE and DISPOSITION correspond to MIME headers Content-Type and
191Content-Disposition respectively, and have this format:
192
193  (VALUE (ATTRIBUTE . VALUE) (ATTRIBUTE . VALUE) ...)
194
195Each VALUE is a string and each ATTRIBUTE is a string.
196
197Consider the following header, for example:
198
199Content-Type: multipart/mixed;
200	boundary=\"----=_NextPart_000_0104_01C617E4.BDEC4C40\"
201
202The corresponding TYPE argument must be:
203
204\(\"multipart/mixed\"
205  (\"boundary\" . \"----=_NextPart_000_0104_01C617E4.BDEC4C40\"))
206
207TRANSFER-ENCODING corresponds to MIME header
208Content-Transfer-Encoding, and is a lower-case string.
209
210DISPLAY is a vector [CURRENT NEW], where CURRENT indicates how
211the header, tag line, and body of the entity are displayed now,
212and NEW indicates how their display should be updated.
213Both elements are vectors [HEADER-DISPLAY TAGLINE-DISPLAY BODY-DISPLAY],
214where each constituent element is a symbol for the corresponding
215item with these values:
216  nil: not displayed
217  t:   displayed by the decoded presentation form
218  raw: displayed by the raw MIME data (for the header and body only)
219
220HEADER and BODY are vectors [BEG END DISPLAY-FLAG], where BEG and
221END are markers that specify the region of the header or body lines
222in RMAIL's data (mbox) buffer, and DISPLAY-FLAG non-nil means that the
223header or body is, by default, displayed by the decoded
224presentation form.
225
226TAGLINE is a vector [TAG BULK-DATA DISPLAY-FLAG], where TAG is a
227string indicating the depth and index number of the entity,
228BULK-DATA is a cons (SIZE . TYPE) indicating the size and type of
229an attached data, DISPLAY-FLAG non-nil means that the tag line is
230displayed by default.
231
232CHILDREN is a list of child MIME-entities.  A \"multipart/*\"
233entity has one or more children.  A \"message/rfc822\" entity
234has just one child.  Any other entity has no child.
235
236HANDLER is a function to insert the entity according to DISPLAY.
237It is called with one argument ENTITY.
238
239TRUNCATED is non-nil if the text of this entity was truncated."
240
241  (vector type disposition transfer-encoding
242	  display header tagline body children handler truncated))
243
244;; Accessors for a MIME-entity object.
245(defsubst rmail-mime-entity-type (entity) (aref entity 0))
246(defsubst rmail-mime-entity-disposition (entity) (aref entity 1))
247(defsubst rmail-mime-entity-transfer-encoding (entity) (aref entity 2))
248(defsubst rmail-mime-entity-display (entity) (aref entity 3))
249(defsubst rmail-mime-entity-header (entity) (aref entity 4))
250(defsubst rmail-mime-entity-tagline (entity) (aref entity 5))
251(defsubst rmail-mime-entity-body (entity) (aref entity 6))
252(defsubst rmail-mime-entity-children (entity) (aref entity 7))
253(defsubst rmail-mime-entity-handler (entity) (aref entity 8))
254(defsubst rmail-mime-entity-truncated (entity) (aref entity 9))
255(defsubst rmail-mime-entity-set-truncated (entity truncated)
256  (aset entity 9 truncated))
257
258;;; Buttons
259
260(defun rmail-mime-save (button)
261  "Save the attachment using info in the BUTTON."
262  (let* ((rmail-mime-mbox-buffer rmail-view-buffer)
263	 (filename (button-get button 'filename))
264	 (directory (button-get button 'directory))
265	 (data (button-get button 'data))
266	 (ofilename filename))
267    (if (and (not (stringp data))
268	     (rmail-mime-entity-truncated data))
269	(unless (y-or-n-p "This entity is truncated; save anyway? ")
270	  (error "Aborted")))
271    (setq filename (expand-file-name
272		    (read-file-name (format "Save as (default: %s): " filename)
273				    directory
274				    (expand-file-name filename directory))
275		    directory))
276    ;; If arg is just a directory, use the default file name, but in
277    ;; that directory (copied from write-file).
278    (if (file-directory-p filename)
279	(setq filename (expand-file-name
280			(file-name-nondirectory ofilename)
281			(file-name-as-directory filename))))
282    (with-temp-buffer
283      (set-buffer-file-coding-system 'no-conversion)
284      ;; Needed e.g. by jka-compr, so if the attachment is a compressed
285      ;; file, the magic signature compares equal with the unibyte
286      ;; signature string recorded in jka-compr-compression-info-list.
287      (set-buffer-multibyte nil)
288      (setq buffer-undo-list t)
289      (if (stringp data)
290	  (insert data)
291	;; DATA is a MIME-entity object.
292	(let ((transfer-encoding (rmail-mime-entity-transfer-encoding data))
293	      (body (rmail-mime-entity-body data)))
294	  (insert-buffer-substring rmail-mime-mbox-buffer
295				   (aref body 0) (aref body 1))
296	  (cond ((string= transfer-encoding "base64")
297		 (ignore-errors (base64-decode-region (point-min) (point-max))))
298		((string= transfer-encoding "quoted-printable")
299		 (quoted-printable-decode-region (point-min) (point-max))))))
300      (write-region nil nil filename nil nil nil t))))
301
302(define-button-type 'rmail-mime-save 'action 'rmail-mime-save)
303
304;; Display options returned by rmail-mime-entity-display.
305;; Value is on of nil, t, raw.
306(defsubst rmail-mime-display-header (disp)  (aref disp 0))
307(defsubst rmail-mime-display-tagline (disp) (aref disp 1))
308(defsubst rmail-mime-display-body (disp)    (aref disp 2))
309
310(defun rmail-mime-entity-segment (pos &optional entity)
311  "Return a vector describing the displayed region of a MIME-entity at POS.
312Optional 2nd argument ENTITY is the MIME-entity at POS.
313The value is a vector [INDEX HEADER TAGLINE BODY END], where
314  INDEX: index into the returned vector indicating where POS is (1..3)
315  HEADER: the position of the beginning of a header
316  TAGLINE: the position of the beginning of a tag line, including
317           the newline that precedes it
318  BODY: the position of the beginning of a body
319  END: the position of the end of the entity."
320  (save-excursion
321    (or entity
322	(setq entity (get-text-property pos 'rmail-mime-entity)))
323    (if (not entity)
324	(vector 1 (point) (point) (point) (point))
325      (let ((current (aref (rmail-mime-entity-display entity) 0))
326	    (beg (if (and (> pos (point-min))
327			  (eq (get-text-property (1- pos) 'rmail-mime-entity)
328			      entity))
329		     (previous-single-property-change pos 'rmail-mime-entity
330						      nil (point-min))
331		   pos))
332	    (index 1)
333	    tagline-beg body-beg end)
334	(goto-char beg)
335	;; If the header is displayed, get past it to the tagline.
336	(if (rmail-mime-display-header current)
337	    (search-forward "\n\n" nil t))
338	(setq tagline-beg (point))
339	(if (>= pos tagline-beg)
340	    (setq index 2))
341	;; If the tagline is displayed, get past it to the body.
342	(if (rmail-mime-display-tagline current)
343	    ;; The next forward-line call must be in sync with how
344	    ;; `rmail-mime-insert-tagline' formats the tagline.  The
345	    ;; body begins after the empty line that ends the tagline.
346	    (forward-line 3))
347	(setq body-beg (point))
348	(if (>= pos body-beg)
349	    (setq index 3))
350	;; If the body is displayed, find its end.
351	(if (rmail-mime-display-body current)
352	    (let ((tag (aref (rmail-mime-entity-tagline entity) 0))
353		  tag2)
354	      (setq end (next-single-property-change beg 'rmail-mime-entity
355						     nil (point-max)))
356	      ;; `tag' is either an empty string or "/n" where n is
357	      ;; the number of the part of the multipart MIME message.
358	      ;; The loop below finds the next location whose
359	      ;; `rmail-mime-entity' property specifies a tag of a
360	      ;; different value.
361	      (while (and (< end (point-max))
362			  (setq entity (get-text-property end 'rmail-mime-entity)
363				tag2 (aref (rmail-mime-entity-tagline entity) 0))
364			  (and (> (length tag2) 0)
365			       (eq (string-match tag tag2) 0)))
366		(setq end (next-single-property-change end 'rmail-mime-entity
367						       nil (point-max)))))
368	  (setq end body-beg))
369	(vector index beg tagline-beg body-beg end)))))
370
371(defun rmail-mime-shown-mode (entity)
372  "Make MIME-entity ENTITY display in the default way."
373  (let ((new (aref (rmail-mime-entity-display entity) 1)))
374    (aset new 0 (aref (rmail-mime-entity-header entity) 2))
375    (aset new 1 (aref (rmail-mime-entity-tagline entity) 2))
376    (aset new 2 (aref (rmail-mime-entity-body entity) 2)))
377  (dolist (child (rmail-mime-entity-children entity))
378    (rmail-mime-shown-mode child)))
379
380(defun rmail-mime-hidden-mode (entity)
381  "Make MIME-entity ENTITY display in hidden mode."
382  (let ((new (aref (rmail-mime-entity-display entity) 1)))
383    (aset new 0 nil)
384    (aset new 1 t)
385    (aset new 2 nil))
386  (dolist (child (rmail-mime-entity-children entity))
387    (rmail-mime-hidden-mode child)))
388
389(defun rmail-mime-raw-mode (entity)
390  "Make MIME-entity ENTITY display in raw mode."
391  (let ((new (aref (rmail-mime-entity-display entity) 1)))
392    (aset new 0 'raw)
393    (aset new 1 nil)
394    (aset new 2 'raw))
395  (dolist (child (rmail-mime-entity-children entity))
396    (rmail-mime-raw-mode child)))
397
398(defun rmail-mime-toggle-raw (&optional state)
399  "Toggle on and off the raw display mode of MIME-entity at point.
400With optional argument STATE, force the specified display mode.
401Use `raw' for raw mode, and any other non-nil value for decoded mode."
402  (let* ((pos (if (eobp) (1- (point-max)) (point)))
403	 (entity (get-text-property pos 'rmail-mime-entity))
404	 (current (aref (rmail-mime-entity-display entity) 0))
405	 (segment (rmail-mime-entity-segment pos entity)))
406    (if (or (eq state 'raw)
407	    (and (not state)
408		 (not (eq (rmail-mime-display-header current) 'raw))))
409	;; Enter the raw mode.
410	(rmail-mime-raw-mode entity)
411      ;; Enter the shown mode.
412      (rmail-mime-shown-mode entity)
413      (let ((inhibit-read-only t)
414	    (modified (buffer-modified-p)))
415	(save-excursion
416	  (goto-char (aref segment 1))
417	  (rmail-mime-insert entity)
418	  (restore-buffer-modified-p modified))))))
419
420(defun rmail-mime-toggle-hidden ()
421  "Hide or show the body of the MIME-entity at point."
422  (interactive)
423  (when (rmail-mime-message-p)
424    (let* ((rmail-mime-mbox-buffer rmail-view-buffer)
425	   (rmail-mime-view-buffer (current-buffer))
426	   (pos (if (eobp) (1- (point-max)) (point)))
427	   (entity (get-text-property pos 'rmail-mime-entity))
428	   (current (aref (rmail-mime-entity-display entity) 0))
429	   (segment (rmail-mime-entity-segment pos entity)))
430      (if (rmail-mime-display-body current)
431	  ;; Enter the hidden mode.
432	  (progn
433	    ;; If point is in the body part, move it to the tagline
434	    ;; (or the header if tagline is not displayed).
435	    (if (= (aref segment 0) 3)
436		(goto-char (aref segment 2)))
437	    (rmail-mime-hidden-mode entity)
438	    ;; If the current entity is the topmost one, display the
439	    ;; header.
440	    (if (and rmail-mime-mbox-buffer (= (aref segment 1) (point-min)))
441		(let ((new (aref (rmail-mime-entity-display entity) 1)))
442		  (aset new 0 t))))
443	;; Query as a warning before showing if truncated.
444	(if (and (not (stringp entity))
445		 (rmail-mime-entity-truncated entity))
446	    (unless (y-or-n-p "This entity is truncated; show anyway? ")
447	      (error "Aborted")))
448	;; Enter the shown mode.
449	(rmail-mime-shown-mode entity)
450	;; Force this body shown.
451	(aset (aref (rmail-mime-entity-display entity) 1) 2 t))
452      (let ((inhibit-read-only t)
453	    (modified (buffer-modified-p))
454	    (rmail-mime-mbox-buffer rmail-view-buffer)
455	    (rmail-mime-view-buffer rmail-buffer))
456	(save-excursion
457	  (goto-char (aref segment 1))
458	  (rmail-mime-insert entity)
459	  (restore-buffer-modified-p modified))))))
460
461(define-key rmail-mode-map "\t" 'forward-button)
462(define-key rmail-mode-map [backtab] 'backward-button)
463(define-key rmail-mode-map "\r" 'rmail-mime-toggle-hidden)
464
465;;; Handlers
466
467(defun rmail-mime-insert-tagline (entity &rest item-list)
468  "Insert a tag line for MIME-entity ENTITY.
469ITEM-LIST is a list of strings or button-elements (list) to add
470to the tag line."
471  ;; Precede the tagline by an empty line to make it a separate
472  ;; paragraph, so that it is aligned to the left margin of the window
473  ;; even if preceded by a right-to-left paragraph.
474  (insert "\n[")
475  (let ((tag (aref (rmail-mime-entity-tagline entity) 0)))
476    (if (> (length tag) 0) (insert (substring tag 1) ":")))
477  (insert (car (rmail-mime-entity-type entity)) " ")
478  (insert-button (let ((new (aref (rmail-mime-entity-display entity) 1)))
479		   (if (rmail-mime-display-body new) "Hide" "Show"))
480		 :type 'rmail-mime-toggle
481		 'help-echo "mouse-2, RET: Toggle show/hide")
482  (dolist (item item-list)
483    (when item
484      (if (stringp item)
485	  (insert item)
486	(apply 'insert-button item))))
487  ;; Follow the tagline by an empty line to make it a separate
488  ;; paragraph, so that the paragraph direction of the following text
489  ;; is determined based on that text.
490  (insert "]\n\n"))
491
492(defun rmail-mime-update-tagline (entity)
493  "Update the current tag line for MIME-entity ENTITY."
494  (let ((inhibit-read-only t)
495	(modified (buffer-modified-p))
496	;; If we are going to show the body, the new button label is
497	;; "Hide".  Otherwise, it's "Show".
498	(label (if (aref (aref (rmail-mime-entity-display entity) 1) 2) "Hide"
499		 "Show"))
500	(button (next-button (point))))
501    ;; Go to the second character of the button "Show" or "Hide".
502    (goto-char (1+ (button-start button)))
503    (setq button (button-at (point)))
504    (save-excursion
505      (insert label)
506      (delete-region (point) (button-end button)))
507    (delete-region (button-start button) (point))
508    (put-text-property (point) (button-end button) 'rmail-mime-entity entity)
509    (restore-buffer-modified-p modified)
510    ;; The following call to forward-line must be in sync with how
511    ;; rmail-mime-insert-tagline formats the tagline.
512    (forward-line 2)))
513
514(defun rmail-mime-insert-header (header)
515  "Decode and insert a MIME-entity header HEADER in the current buffer.
516HEADER is a vector [BEG END DEFAULT-STATUS].
517See `rmail-mime-entity' for details."
518  (let ((pos (point))
519	(last-coding-system-used nil))
520    (save-restriction
521      (narrow-to-region pos pos)
522      (with-current-buffer rmail-mime-mbox-buffer
523	(let ((rmail-buffer rmail-mime-mbox-buffer)
524	      (rmail-view-buffer rmail-mime-view-buffer))
525	  (save-excursion
526	    (goto-char (aref header 0))
527	    (rmail-copy-headers (point) (aref header 1)))))
528      (rfc2047-decode-region pos (point))
529      (if (and last-coding-system-used (not rmail-mime-coding-system))
530	  (setq rmail-mime-coding-system (cons last-coding-system-used nil)))
531      (goto-char (point-min))
532      (rmail-highlight-headers)
533      (goto-char (point-max))
534      (insert "\n"))))
535
536(defun rmail-mime-find-header-encoding (header)
537  "Return the last coding system used to decode HEADER.
538HEADER is a header component of a MIME-entity object (see
539`rmail-mime-entity')."
540  (with-temp-buffer
541    (let ((buf (current-buffer)))
542      (with-current-buffer rmail-mime-mbox-buffer
543	(let ((last-coding-system-used nil)
544	      (rmail-buffer rmail-mime-mbox-buffer)
545	      (rmail-view-buffer buf))
546	  (save-excursion
547	    (goto-char (aref header 0))
548	    (rmail-copy-headers (point) (aref header 1)))))
549      (rfc2047-decode-region (point-min) (point-max))
550      last-coding-system-used)))
551
552(defun rmail-mime-text-handler (content-type
553				content-disposition
554				content-transfer-encoding)
555  "Handle the current buffer as a plain text MIME part."
556  (rmail-mime-insert-text
557   (rmail-mime-entity content-type content-disposition
558		      content-transfer-encoding
559		      (vector (vector nil nil nil) (vector nil nil t))
560		      (vector nil nil nil) (vector "" (cons nil nil) t)
561		      (vector nil nil nil) nil 'rmail-mime-insert-text))
562  t)
563
564(defun rmail-mime-insert-decoded-text (entity)
565  "Decode and insert the text body of MIME-entity ENTITY."
566  (let* ((content-type (rmail-mime-entity-type entity))
567	 (charset (cdr (assq 'charset (cdr content-type))))
568	 (coding-system (if charset
569			    (coding-system-from-name charset)))
570	 (body (rmail-mime-entity-body entity))
571	 (pos (point)))
572    (or (and coding-system (coding-system-p coding-system))
573	(setq coding-system 'undecided))
574    (if (stringp (aref body 0))
575	(insert (aref body 0))
576      (let ((transfer-encoding (rmail-mime-entity-transfer-encoding entity)))
577	(insert-buffer-substring rmail-mime-mbox-buffer
578				 (aref body 0) (aref body 1))
579	(cond ((string= transfer-encoding "base64")
580	       (ignore-errors (base64-decode-region pos (point))))
581	      ((string= transfer-encoding "quoted-printable")
582	       (quoted-printable-decode-region pos (point))))))
583    (decode-coding-region pos (point) coding-system)
584    (if (and
585	 (or (not rmail-mime-coding-system) (consp rmail-mime-coding-system))
586	 (not (eq (coding-system-base coding-system) 'us-ascii)))
587	(setq rmail-mime-coding-system coding-system))
588    (or (bolp) (insert "\n"))))
589
590(defun rmail-mime-insert-text (entity)
591  "Presentation handler for a plain text MIME entity."
592  (let ((current (aref (rmail-mime-entity-display entity) 0))
593	(new (aref (rmail-mime-entity-display entity) 1))
594	(header (rmail-mime-entity-header entity))
595	(tagline (rmail-mime-entity-tagline entity))
596	(body (rmail-mime-entity-body entity))
597	(beg (point))
598	(segment (rmail-mime-entity-segment (point) entity)))
599
600    (or (integerp (aref body 0)) (markerp (aref body 0))
601	(let ((data (buffer-string)))
602	  (aset body 0 data)
603	  (delete-region (point-min) (point-max))))
604
605    ;; header
606    (if (eq (rmail-mime-display-header current)
607	    (rmail-mime-display-header new))
608	(goto-char (aref segment 2))
609      (if (rmail-mime-display-header current)
610	  (delete-char (- (aref segment 2) (aref segment 1))))
611      (if (rmail-mime-display-header new)
612	  (rmail-mime-insert-header header)))
613    ;; tagline
614    (if (eq (rmail-mime-display-tagline current)
615	    (rmail-mime-display-tagline new))
616	(if (or (not (rmail-mime-display-tagline current))
617		(eq (rmail-mime-display-body current)
618		    (rmail-mime-display-body new)))
619	    (forward-char (- (aref segment 3) (aref segment 2)))
620	  (rmail-mime-update-tagline entity))
621      (if (rmail-mime-display-tagline current)
622	  (delete-char (- (aref segment 3) (aref segment 2))))
623      (if (rmail-mime-display-tagline new)
624	  (rmail-mime-insert-tagline entity)))
625    ;; body
626    (if (eq (rmail-mime-display-body current)
627	    (rmail-mime-display-body new))
628	(forward-char (- (aref segment 4) (aref segment 3)))
629      (if (rmail-mime-display-body current)
630	  (delete-char (- (aref segment 4) (aref segment 3))))
631      (if (rmail-mime-display-body new)
632	  (rmail-mime-insert-decoded-text entity)))
633    (put-text-property beg (point) 'rmail-mime-entity entity)))
634
635(defun rmail-mime-insert-image (entity)
636  "Decode and insert the image body of MIME-entity ENTITY."
637  (let* ((content-type (car (rmail-mime-entity-type entity)))
638	 (bulk-data (aref (rmail-mime-entity-tagline entity) 1))
639	 (body (rmail-mime-entity-body entity))
640	 data)
641    (if (stringp (aref body 0))
642	(setq data (aref body 0))
643      (let ((rmail-mime-mbox-buffer rmail-view-buffer)
644	    (transfer-encoding (rmail-mime-entity-transfer-encoding entity)))
645	(with-temp-buffer
646	  (set-buffer-multibyte nil)
647	  (setq buffer-undo-list t)
648	  (insert-buffer-substring rmail-mime-mbox-buffer
649				   (aref body 0) (aref body 1))
650	  (cond ((string= transfer-encoding "base64")
651		 (ignore-errors (base64-decode-region (point-min) (point-max))))
652		((string= transfer-encoding "quoted-printable")
653		 (quoted-printable-decode-region (point-min) (point-max))))
654	  (setq data
655		(buffer-substring-no-properties (point-min) (point-max))))))
656    (insert-image (create-image data (cdr bulk-data) t))
657    (insert "\n")))
658
659(defun rmail-mime-insert-html (entity)
660  "Decode, render, and insert html from MIME-entity ENTITY."
661  (let ((body (rmail-mime-entity-body entity))
662	(transfer-encoding (rmail-mime-entity-transfer-encoding entity))
663	(charset (cdr (assq 'charset (cdr (rmail-mime-entity-type entity)))))
664	(buffer (current-buffer))
665	(case-fold-search t)
666	coding-system)
667    (if charset (setq coding-system (coding-system-from-name charset)))
668    (or (and coding-system (coding-system-p coding-system))
669	(setq coding-system 'undecided))
670    (with-temp-buffer
671      (set-buffer-multibyte nil)
672      (setq buffer-undo-list t)
673      (insert-buffer-substring rmail-mime-mbox-buffer
674			       (aref body 0) (aref body 1))
675      (cond ((string= transfer-encoding "base64")
676	     (ignore-errors (base64-decode-region (point-min) (point-max))))
677	    ((string= transfer-encoding "quoted-printable")
678	     (quoted-printable-decode-region (point-min) (point-max))))
679      ;; Some broken MUAs state the charset only in the HTML <head>,
680      ;; so if we don't have a non-trivial coding-system at this
681      ;; point, make one last attempt to find it there.
682      (if (eq coding-system 'undecided)
683	  (save-excursion
684	    (goto-char (point-min))
685	    (when (re-search-forward
686		   "^<html><head><meta[^;]*; charset=\\([-a-zA-Z0-9]+\\)"
687		   nil t)
688	      (setq coding-system (coding-system-from-name (match-string 1)))
689	      (or (and coding-system (coding-system-p coding-system))
690		  (setq coding-system 'undecided)))
691	    ;; Finally, let them manually force decoding if they know it.
692	    (if (and (eq coding-system 'undecided)
693		     (not (null coding-system-for-read)))
694		(setq coding-system coding-system-for-read))))
695      (decode-coding-region (point-min) (point) coding-system)
696      (if (and
697	   (or (not rmail-mime-coding-system) (consp rmail-mime-coding-system))
698	   (not (eq (coding-system-base coding-system) 'us-ascii)))
699	  (setq rmail-mime-coding-system coding-system))
700      ;; Convert html in temporary buffer to text and insert in original buffer
701      (let ((source-buffer (current-buffer)))
702	(with-current-buffer buffer
703	  (let ((start (point)))
704	    (if rmail-mime-render-html-function
705		(funcall rmail-mime-render-html-function source-buffer)
706	      (insert-buffer-substring source-buffer))
707	    (rmail-mime-fix-inserted-faces start)))))))
708
709(declare-function libxml-parse-html-region "xml.c"
710		  (start end &optional base-url discard-comments))
711
712(defun rmail-mime-render-html-shr (source-buffer)
713  (let ((dom (with-current-buffer source-buffer
714	       (libxml-parse-html-region (point-min) (point-max))))
715	;; Image retrieval happens asynchronously, but meanwhile
716	;; `rmail-swap-buffers' may have been run, leaving
717	;; `shr-image-fetched' trying to insert the image in the wrong buffer.
718	(shr-inhibit-images t)
719	;; Bind shr-width to nil to force shr-insert-document break
720	;; the lines at the window margin.  The default is
721	;; fill-column, whose default value is too small, and screws
722	;; up display of the quoted messages.
723	shr-width)
724    (shr-insert-document dom)))
725
726(defun rmail-mime-render-html-lynx (source-buffer)
727  (let ((destination-buffer (current-buffer)))
728    (with-current-buffer source-buffer
729      (call-process-region (point-min) (point-max)
730			   "lynx" nil destination-buffer nil
731			   "-stdin" "-dump" "-force_html"
732			   "-dont_wrap_pre" "-width=70"))))
733
734;; Put font-lock-face properties matching face properties on text
735;; inserted, e.g., by shr, in text from START to point.
736(defun rmail-mime-fix-inserted-faces (start)
737  (while (< start (point))
738    (let ((face (get-text-property start 'face))
739	  (next (next-single-property-change
740		 start 'face (current-buffer) (point))))
741      (if face				; anything to do?
742	  (put-text-property start next 'font-lock-face face))
743      (setq start next))))
744
745(defun rmail-mime-toggle-button (button)
746  "Hide or show the body of the MIME-entity associated with BUTTON."
747  (save-excursion
748    (goto-char (button-start button))
749    (rmail-mime-toggle-hidden)))
750
751(define-button-type 'rmail-mime-toggle 'action 'rmail-mime-toggle-button)
752
753
754(defun rmail-mime-bulk-handler (content-type
755				content-disposition
756				content-transfer-encoding)
757  "Handle the current buffer as an attachment to download.
758For images that Emacs is capable of displaying, the behavior
759depends upon the value of `rmail-mime-show-images'."
760  (rmail-mime-insert-bulk
761   (rmail-mime-entity content-type content-disposition content-transfer-encoding
762		      (vector (vector nil nil nil) (vector nil t nil))
763		      (vector nil nil nil) (vector "" (cons nil nil) t)
764		      (vector nil nil nil) nil 'rmail-mime-insert-bulk)))
765
766(defun rmail-mime-set-bulk-data (entity)
767  "Setup the information about the attachment object for MIME-entity ENTITY.
768The value is non-nil if and only if the attachment object should be shown
769directly."
770  (let ((content-type (car (rmail-mime-entity-type entity)))
771	(size (cdr (assq 'size (cdr (rmail-mime-entity-disposition entity)))))
772	(bulk-data (aref (rmail-mime-entity-tagline entity) 1))
773	(body (rmail-mime-entity-body entity))
774	type to-show)
775    (cond (size
776	   (setq size (string-to-number size)))
777	  ((stringp (aref body 0))
778	   (setq size (length (aref body 0))))
779	  (t
780	   ;; Rough estimation of the size.
781	   (let ((encoding (rmail-mime-entity-transfer-encoding entity)))
782	     (setq size (- (aref body 1) (aref body 0)))
783	     (cond ((string= encoding "base64")
784		    (setq size (/ (* size 3) 4)))
785		   ((string= encoding "quoted-printable")
786		    (setq size (/ (* size 7) 3)))))))
787
788    (cond
789     ((string-match "text/html" content-type)
790      (setq type 'html))
791     ((string-match "text/" content-type)
792      (setq type 'text))
793     ((string-match "image/\\(.*\\)" content-type)
794      (setq type (image-type-from-file-name
795		  (concat "." (match-string 1 content-type))))
796      (if (and (boundp 'image-types)
797	       (memq type image-types)
798	       (image-type-available-p type))
799	  (if (and rmail-mime-show-images
800		   (not (eq rmail-mime-show-images 'button))
801		   (or (not (numberp rmail-mime-show-images))
802		       (< size rmail-mime-show-images)))
803	      (setq to-show t))
804	(setq type nil))))
805    (setcar bulk-data size)
806    (setcdr bulk-data type)
807    to-show))
808
809(defun rmail-mime-insert-bulk (entity)
810  "Presentation handler for an attachment MIME entity."
811  (let* ((content-type (rmail-mime-entity-type entity))
812	 (content-disposition (rmail-mime-entity-disposition entity))
813	 (current (aref (rmail-mime-entity-display entity) 0))
814	 (new (aref (rmail-mime-entity-display entity) 1))
815	 (header (rmail-mime-entity-header entity))
816	 (tagline (rmail-mime-entity-tagline entity))
817	 (bulk-data (aref tagline 1))
818	 (body (rmail-mime-entity-body entity))
819	 ;; Find the default directory for this media type.
820	 (directory (or (catch 'directory
821			  (dolist (entry rmail-mime-attachment-dirs-alist)
822			    (when (string-match (car entry) (car content-type))
823			      (dolist (dir (cdr entry))
824				(when (file-directory-p dir)
825				  (throw 'directory dir))))))
826			"~"))
827	 (filename (or (cdr (assq 'name (cdr content-type)))
828		       (cdr (assq 'filename (cdr content-disposition)))
829		       "noname"))
830	 (units '(B kB MB GB))
831	 (segment (rmail-mime-entity-segment (point) entity))
832	 beg data size)
833
834    (if (or (integerp (aref body 0)) (markerp (aref body 0)))
835	(setq data entity
836	      size (car bulk-data))
837      (if (stringp (aref body 0))
838	  (setq data (aref body 0))
839	(setq data (buffer-string))
840        (cl-assert (not (multibyte-string-p data)))
841	(aset body 0 data)
842	(rmail-mime-set-bulk-data entity)
843	(delete-region (point-min) (point-max)))
844      (setq size (length data)))
845    (while (and (> size 1024.0) ; cribbed from gnus-agent-expire-done-message
846		(cdr units))
847      (setq size (/ size 1024.0)
848	    units (cdr units)))
849
850    (setq beg (point))
851
852    ;; header
853    (if (eq (rmail-mime-display-header current)
854	    (rmail-mime-display-header new))
855	(goto-char (aref segment 2))
856      (if (rmail-mime-display-header current)
857	  (delete-char (- (aref segment 2) (aref segment 1))))
858      (if (rmail-mime-display-header new)
859	  (rmail-mime-insert-header header)))
860
861    ;; tagline
862    (if (eq (rmail-mime-display-tagline current)
863	    (rmail-mime-display-tagline new))
864	(if (or (not (rmail-mime-display-tagline current))
865		(eq (rmail-mime-display-body current)
866		    (rmail-mime-display-body new)))
867	    (forward-char (- (aref segment 3) (aref segment 2)))
868	  (rmail-mime-update-tagline entity))
869      (if (rmail-mime-display-tagline current)
870	  (delete-char (- (aref segment 3) (aref segment 2))))
871      (if (rmail-mime-display-tagline new)
872	  (rmail-mime-insert-tagline
873	   entity
874	   " Save:"
875	   (list filename
876		 :type 'rmail-mime-save
877		 'help-echo "mouse-2, RET: Save attachment"
878		 'filename filename
879		 'directory (file-name-as-directory directory)
880		 'data data)
881	   (format " (%.0f%s)" size (car units))
882	   ;; We don't need this button because the "type" string of a
883	   ;; tagline is the button to do this.
884	   ;; (if (cdr bulk-data)
885	   ;;     " ")
886	   ;; (if (cdr bulk-data)
887	   ;;     (list "Toggle show/hide"
888	   ;; 	     :type 'rmail-mime-image
889	   ;; 	     'help-echo "mouse-2, RET: Toggle show/hide"
890	   ;; 	     'image-type (cdr bulk-data)
891	   ;; 	     'image-data data))
892	   )))
893    ;; body
894    (if (eq (rmail-mime-display-body current)
895	    (rmail-mime-display-body new))
896	(forward-char (- (aref segment 4) (aref segment 3)))
897      (if (rmail-mime-display-body current)
898	  (delete-char (- (aref segment 4) (aref segment 3))))
899      (if (rmail-mime-display-body new)
900	  (cond ((eq (cdr bulk-data) 'text)
901		 (rmail-mime-insert-decoded-text entity))
902		((eq (cdr bulk-data) 'html)
903		 ;; Render HTML if display single message, but if searching
904		 ;; don't render but just search HTML itself.
905		 (if rmail-mime-searching
906		     (rmail-mime-insert-decoded-text entity)
907		   (rmail-mime-insert-html entity)))
908		((cdr bulk-data)
909		 (rmail-mime-insert-image entity))
910		(t
911		 ;; As we don't know how to display the body, just
912		 ;; insert it as a text.
913		 (rmail-mime-insert-decoded-text entity)))))
914    (put-text-property beg (point) 'rmail-mime-entity entity)))
915
916(defun rmail-mime-multipart-handler (content-type
917				     content-disposition
918				     content-transfer-encoding)
919  "Handle the current buffer as a multipart MIME body.
920The current buffer should be narrowed to the body.  CONTENT-TYPE,
921CONTENT-DISPOSITION, and CONTENT-TRANSFER-ENCODING are the values
922of the respective parsed headers.  See `rmail-mime-handle' for their
923format."
924  (rmail-mime-process-multipart
925   content-type content-disposition content-transfer-encoding nil)
926  t)
927
928(defun rmail-mime-process-multipart (content-type
929				     content-disposition
930				     content-transfer-encoding
931				     parse-tag)
932  "Process the current buffer as a multipart MIME body.
933
934If PARSE-TAG is nil, modify the current buffer directly for
935showing the MIME body and return nil.
936
937Otherwise, PARSE-TAG is a string indicating the depth and index
938number of the entity.  In this case, parse the current buffer and
939return a list of MIME-entity objects.
940
941The other arguments are the same as `rmail-mime-multipart-handler'."
942  ;; Some MUAs start boundaries with "--", while it should start
943  ;; with "CRLF--", as defined by RFC 2046:
944  ;;    The boundary delimiter MUST occur at the beginning of a line,
945  ;;    i.e., following a CRLF, and the initial CRLF is considered to
946  ;;    be attached to the boundary delimiter line rather than part
947  ;;    of the preceding part.
948  ;; We currently don't handle that.
949  (let ((boundary (cdr (assq 'boundary content-type)))
950	(subtype (cadr (split-string (car content-type) "/")))
951	(index 0)
952	beg end next entities truncated last)
953    (unless boundary
954      (rmail-mm-get-boundary-error-message
955       "No boundary defined" content-type content-disposition
956       content-transfer-encoding))
957    (setq boundary (concat "\n--" boundary))
958    ;; Hide the body before the first bodypart
959    (goto-char (point-min))
960    (when (and (search-forward boundary nil t)
961	       (looking-at "[ \t]*\n"))
962      (if parse-tag
963	  (narrow-to-region (match-end 0) (point-max))
964	(delete-region (point-min) (match-end 0))))
965
966    ;; Change content-type to the proper default one for the children.
967    (cond ((string-match "mixed" subtype)
968	   (setq content-type '("text/plain")))
969	  ((string-match "digest" subtype)
970	   (setq content-type '("message/rfc822")))
971	  (t
972	   (setq content-type nil)))
973
974    ;; Loop over all body parts, where beg points at the beginning of
975    ;; the part and end points at the end of the part.  next points at
976    ;; the beginning of the next part.  The current point is just
977    ;; after the boundary tag.
978    (setq beg (point-min))
979
980    (while (or (and (search-forward boundary nil t)
981		    (setq truncated nil end (match-beginning 0)))
982	       ;; If the boundary does not appear at all,
983	       ;; the message was truncated.
984	       ;; Handle the rest of the truncated message
985	       ;; (if it isn't empty) by pretending that the boundary
986	       ;; appears at the end of the message.
987	       ;; We use `last' to distinguish this from the more
988	       ;; likely situation of there being an epilogue
989	       ;; after the last boundary, which should be ignored.
990	       ;; See rmailmm-test-multipart-handler for an example,
991	       ;; and also bug#10101.
992	       (and (not last)
993		    (save-excursion
994		      (skip-chars-forward "\n")
995		      (> (point-max) (point)))
996		    (setq truncated t end (point-max))))
997      ;; If this is the last boundary according to RFC 2046, hide the
998      ;; epilogue, else hide the boundary only.  Use a marker for
999      ;; `next' because `rmail-mime-show' may change the buffer.
1000      (cond ((looking-at "--[ \t]*$")
1001	     (setq next (point-max-marker)
1002		   last t))
1003	    ((looking-at "[ \t]*\n")
1004	     (setq next (copy-marker (match-end 0) t)))
1005	    (truncated
1006	     ;; We're handling what's left of a truncated message.
1007	     (setq next (point-max-marker)))
1008	    (t
1009	     ;; The original code signaled an error as below, but
1010	     ;; this line may be a boundary of nested multipart.  So,
1011	     ;; we just set `next' to nil to skip this line
1012	     ;; (rmail-mm-get-boundary-error-message
1013	     ;;  "Malformed boundary" content-type content-disposition
1014	     ;;  content-transfer-encoding)
1015	     (setq next nil)))
1016
1017      (when next
1018	(setq index (1+ index))
1019	;; Handle the part.
1020	(if parse-tag
1021	    (save-restriction
1022	      (narrow-to-region beg end)
1023	      (let ((child (rmail-mime-process
1024			    nil (format "%s/%d" parse-tag index)
1025			    content-type content-disposition)))
1026		;; Display a tagline.
1027		(aset (aref (rmail-mime-entity-display child) 1) 1
1028		      (aset (rmail-mime-entity-tagline child) 2 t))
1029		(rmail-mime-entity-set-truncated child truncated)
1030		(push child entities)))
1031
1032	  (delete-region end next)
1033	  (save-restriction
1034	    (narrow-to-region beg end)
1035	    (rmail-mime-show)))
1036	(goto-char (setq beg next))))
1037
1038    (when parse-tag
1039      (setq entities (nreverse entities))
1040      (if (string-match "alternative" subtype)
1041	  ;; Find the best entity to show, and hide all the others.
1042	  ;; If rmail-mime-prefer-html is set, html is best, then plain.
1043	  ;; If not, plain is best, then html.
1044	  ;; Then comes any other text part.
1045	  ;; If thereto of the same type, earlier entities in the message (later
1046	  ;; in the reverse list) are preferred.
1047	  (let (best best-priority)
1048	    (dolist (child entities)
1049	      (if (string= (or (car (rmail-mime-entity-disposition child))
1050			       (car content-disposition))
1051			   "inline")
1052		  (let ((type (car (rmail-mime-entity-type child))))
1053		    (if (string-match "text/" type)
1054			;; Consider all inline text parts
1055			(let ((priority
1056			       (cond ((string-match "text/html" type)
1057				      (if rmail-mime-prefer-html 1 2))
1058				     ((string-match "text/plain" type)
1059				      (if rmail-mime-prefer-html 2 1))
1060				     (t 3))))
1061			  (if (or (null best) (<= priority best-priority))
1062			      (setq best child
1063				    best-priority priority)))))))
1064	    (dolist (child entities)
1065	      (unless (eq best child)
1066		(aset (rmail-mime-entity-body child) 2 nil)
1067		(rmail-mime-hidden-mode child)))))
1068      entities)))
1069
1070(defun rmail-mime-insert-multipart (entity)
1071  "Presentation handler for a multipart MIME entity."
1072  (let ((current (aref (rmail-mime-entity-display entity) 0))
1073	(new (aref (rmail-mime-entity-display entity) 1))
1074	(header (rmail-mime-entity-header entity))
1075	(tagline (rmail-mime-entity-tagline entity))
1076	(body (rmail-mime-entity-body entity))
1077	(beg (point))
1078	(segment (rmail-mime-entity-segment (point) entity)))
1079    ;; header
1080    (if (eq (rmail-mime-display-header current)
1081	    (rmail-mime-display-header new))
1082	(goto-char (aref segment 2))
1083      (if (rmail-mime-display-header current)
1084	  (delete-char (- (aref segment 2) (aref segment 1))))
1085      (if (rmail-mime-display-header new)
1086	  (rmail-mime-insert-header header)))
1087    ;; tagline
1088    (if (eq (rmail-mime-display-tagline current)
1089	    (rmail-mime-display-tagline new))
1090	(if (or (not (rmail-mime-display-tagline current))
1091		(eq (rmail-mime-display-body current)
1092		    (rmail-mime-display-body new)))
1093	    (forward-char (- (aref segment 3) (aref segment 2)))
1094	  (rmail-mime-update-tagline entity))
1095      (if (rmail-mime-display-tagline current)
1096	  (delete-char (- (aref segment 3) (aref segment 2))))
1097      (if (rmail-mime-display-tagline new)
1098	  (rmail-mime-insert-tagline entity)))
1099
1100    (put-text-property beg (point) 'rmail-mime-entity entity)
1101
1102    ;; body
1103    (if (eq (rmail-mime-display-body current)
1104	    (rmail-mime-display-body new))
1105	(forward-char (- (aref segment 4) (aref segment 3)))
1106      (dolist (child (rmail-mime-entity-children entity))
1107	(rmail-mime-insert child)))
1108    entity))
1109
1110;;; Main code
1111
1112(defun rmail-mime-handle (content-type
1113			  content-disposition
1114			  content-transfer-encoding)
1115  "Handle the current buffer as a MIME part.
1116The current buffer should be narrowed to the respective body, and
1117point should be at the beginning of the body.
1118
1119CONTENT-TYPE, CONTENT-DISPOSITION, and CONTENT-TRANSFER-ENCODING
1120are the values of the respective parsed headers.  The latter should
1121be lower-case.  The parsed headers for CONTENT-TYPE and CONTENT-DISPOSITION
1122have the form
1123
1124  (VALUE . ALIST)
1125
1126In other words:
1127
1128  (VALUE (ATTRIBUTE . VALUE) (ATTRIBUTE . VALUE) ...)
1129
1130VALUE is a string and ATTRIBUTE is a symbol.
1131
1132Consider the following header, for example:
1133
1134Content-Type: multipart/mixed;
1135	boundary=\"----=_NextPart_000_0104_01C617E4.BDEC4C40\"
1136
1137The parsed header value:
1138
1139\(\"multipart/mixed\"
1140  (\"boundary\" . \"----=_NextPart_000_0104_01C617E4.BDEC4C40\"))"
1141  ;; Handle the content transfer encodings we know.  Unknown transfer
1142  ;; encodings will be passed on to the various handlers.
1143  (cond ((string= content-transfer-encoding "base64")
1144	 (when (ignore-errors
1145		 (base64-decode-region (point) (point-max)))
1146	   (setq content-transfer-encoding nil)))
1147	((string= content-transfer-encoding "quoted-printable")
1148	 (quoted-printable-decode-region (point) (point-max))
1149	 (setq content-transfer-encoding nil))
1150	((string= content-transfer-encoding "8bit")
1151	 ;; FIXME: Is this the correct way?
1152         ;; No, of course not, it just means there's no decoding to do.
1153	 ;; (set-buffer-multibyte nil)
1154         (setq content-transfer-encoding nil)
1155         ))
1156  ;; Inline stuff requires work.  Attachments are handled by the bulk
1157  ;; handler.
1158  (if (string= "inline" (car content-disposition))
1159      (let ((stop nil))
1160	(dolist (entry rmail-mime-media-type-handlers-alist)
1161	  (when (and (string-match (car entry) (car content-type)) (not stop))
1162	    (progn
1163	      (setq stop (funcall (cadr entry) content-type
1164				  content-disposition
1165				  content-transfer-encoding))))))
1166    ;; Everything else is an attachment.
1167    (rmail-mime-bulk-handler content-type
1168		       content-disposition
1169		       content-transfer-encoding))
1170  (save-restriction
1171    (widen)
1172    (let ((entity (get-text-property (1- (point)) 'rmail-mime-entity))
1173	  current new)
1174      (when entity
1175	(setq current (aref (rmail-mime-entity-display entity) 0)
1176	      new (aref (rmail-mime-entity-display entity) 1))
1177	(dotimes (i 3)
1178	  (aset current i (aref new i)))))))
1179
1180(defun rmail-mime-show (&optional show-headers)
1181  "Handle the current buffer as a MIME message.
1182If SHOW-HEADERS is non-nil, then the headers of the current part
1183will shown as usual for a MIME message.  The headers are also
1184shown for the content type message/rfc822.  This function will be
1185called recursively if multiple parts are available.
1186
1187The current buffer must contain a single message.  It will be
1188modified."
1189  (rmail-mime-process show-headers nil))
1190
1191(defun rmail-mime-process (show-headers parse-tag &optional
1192					default-content-type
1193					default-content-disposition)
1194  (let ((end (point-min))
1195	content-type
1196	content-transfer-encoding
1197	content-disposition)
1198    ;; `point-min' returns the beginning and `end' points at the end
1199    ;; of the headers.
1200    (goto-char (point-min))
1201    ;; If we're showing a part without headers, then it will start
1202    ;; with a newline.
1203    (if (eq (char-after) ?\n)
1204	(setq end (1+ (point)))
1205      (when (search-forward "\n\n" nil t)
1206	(setq end (match-end 0))
1207	(save-restriction
1208	  (narrow-to-region (point-min) end)
1209	  ;; FIXME: Default disposition of the multipart entities should
1210	  ;; be inherited.
1211	  (setq content-type
1212		(mail-fetch-field "Content-Type")
1213		content-transfer-encoding
1214		(mail-fetch-field "Content-Transfer-Encoding")
1215		content-disposition
1216		(mail-fetch-field "Content-Disposition")))))
1217    ;; Per RFC 2045, C-T-E is case insensitive (bug#5070), but the others
1218    ;; are not completely so.  Hopefully mail-header-parse-* DTRT.
1219    (if content-transfer-encoding
1220	(setq content-transfer-encoding (downcase content-transfer-encoding)))
1221    (setq content-type
1222	  (if content-type
1223	      (or (mail-header-parse-content-type content-type)
1224		  '("text/plain"))
1225	    (or default-content-type '("text/plain"))))
1226    (setq content-disposition
1227	  (if content-disposition
1228	      (mail-header-parse-content-disposition content-disposition)
1229	    ;; If none specified, we are free to choose what we deem
1230	    ;; suitable according to RFC 2183.  We like inline.
1231	    (or default-content-disposition '("inline"))))
1232    ;; Unrecognized disposition types are to be treated like
1233    ;; attachment according to RFC 2183.
1234    (unless (member (car content-disposition) '("inline" "attachment"))
1235      (setq content-disposition '("attachment")))
1236
1237    (if parse-tag
1238	(let* ((is-inline (string= (car content-disposition) "inline"))
1239	       (hdr-end (copy-marker end))
1240	       (header (vector (point-min-marker) hdr-end nil))
1241	       (tagline (vector parse-tag (cons nil nil) t))
1242	       (body (vector hdr-end (point-max-marker) is-inline))
1243	       (new (vector (aref header 2) (aref tagline 2) (aref body 2)))
1244	       children handler entity)
1245	  (cond ((string-match "multipart/.*" (car content-type))
1246		 (save-restriction
1247		   (narrow-to-region (1- end) (point-max))
1248		   (if (zerop (length parse-tag)) ; top level of message
1249		       (aset new 1 (aset tagline 2 nil))) ; don't show tagline
1250		   (setq children (rmail-mime-process-multipart
1251				   content-type
1252				   content-disposition
1253				   content-transfer-encoding
1254				   parse-tag)
1255			 handler 'rmail-mime-insert-multipart)))
1256		((string-match "message/rfc822" (car content-type))
1257		 (save-restriction
1258		   (narrow-to-region end (point-max))
1259		   (let* ((msg (rmail-mime-process t parse-tag
1260						   '("text/plain") '("inline")))
1261			  (msg-new (aref (rmail-mime-entity-display msg) 1)))
1262		     ;; Show header of the child.
1263		     (aset msg-new 0 t)
1264		     (aset (rmail-mime-entity-header msg) 2 t)
1265		     ;; Hide tagline of the child.
1266		     (aset msg-new 1 nil)
1267		     (aset (rmail-mime-entity-tagline msg) 2 nil)
1268		     (setq children (list msg)
1269			   handler 'rmail-mime-insert-multipart))))
1270		((and is-inline (string-match "text/html" (car content-type)))
1271		 ;; Display tagline, so part can be detached
1272		 (aset new 1 (aset tagline 2 t))
1273		 (aset new 2 (aset body 2 t)) ; display body also.
1274		 (setq handler 'rmail-mime-insert-bulk))
1275		;; Inline non-HTML text
1276		((and is-inline (string-match "text/" (car content-type)))
1277		 ;; Don't need a tagline.
1278		 (aset new 1 (aset tagline 2 nil))
1279		 (setq handler 'rmail-mime-insert-text))
1280		(t
1281		 ;; Force hidden mode.
1282		 (aset new 1 (aset tagline 2 t))
1283		 (aset new 2 (aset body 2 nil))
1284		 (setq handler 'rmail-mime-insert-bulk)))
1285	  (setq entity (rmail-mime-entity content-type
1286					  content-disposition
1287					  content-transfer-encoding
1288					  (vector (vector nil nil nil) new)
1289					  header tagline body children handler))
1290	  (if (and (eq handler 'rmail-mime-insert-bulk)
1291		   (rmail-mime-set-bulk-data entity))
1292	      ;; Show the body.
1293	      (aset new 2 (aset body 2 t)))
1294	  entity)
1295
1296      ;; Hide headers and handle the part.
1297      (put-text-property (point-min) (point-max) 'rmail-mime-entity
1298			 (rmail-mime-entity
1299			  content-type content-disposition
1300			  content-transfer-encoding
1301			  (vector (vector 'raw nil 'raw) (vector 'raw nil 'raw))
1302			  (vector nil nil 'raw) (vector "" (cons nil nil) nil)
1303			  (vector nil nil 'raw) nil nil))
1304      (save-restriction
1305	(cond ((string= (car content-type) "message/rfc822")
1306	       (narrow-to-region end (point-max)))
1307	      ((not show-headers)
1308	       (delete-region (point-min) end)))
1309	(rmail-mime-handle content-type content-disposition
1310			   content-transfer-encoding)))))
1311
1312(defun rmail-mime-parse ()
1313  "Parse the current Rmail message as a MIME message.
1314The value is a MIME-entity object (see `rmail-mime-entity').
1315If an error occurs, return an error message string."
1316  (let ((rmail-mime-mbox-buffer (if (rmail-buffers-swapped-p)
1317				    rmail-view-buffer
1318				  (current-buffer))))
1319    (condition-case err
1320	(with-current-buffer rmail-mime-mbox-buffer
1321	  (save-excursion
1322	    (goto-char (point-min))
1323	    (let* ((entity (rmail-mime-process t ""
1324					       '("text/plain") '("inline")))
1325		   (new (aref (rmail-mime-entity-display entity) 1)))
1326	      ;; Show header.
1327	      (aset new 0 (aset (rmail-mime-entity-header entity) 2 t))
1328	      entity)))
1329      (error (format "%s" err)))))
1330
1331(defun rmail-mime-insert (entity)
1332  "Insert a MIME-entity ENTITY in the current buffer.
1333
1334This function will be called recursively if multiple parts are
1335available."
1336  (let ((current (aref (rmail-mime-entity-display entity) 0))
1337	(new (aref (rmail-mime-entity-display entity) 1)))
1338    (if (not (eq (rmail-mime-display-header new) 'raw))
1339	;; Not a raw-mode.  Each handler should handle it.
1340	(funcall (rmail-mime-entity-handler entity) entity)
1341      (let ((header (rmail-mime-entity-header entity))
1342	    (tagline (rmail-mime-entity-tagline entity))
1343	    (body (rmail-mime-entity-body entity))
1344	    (beg (point))
1345	    (segment (rmail-mime-entity-segment (point) entity)))
1346	;; header
1347	(if (eq (rmail-mime-display-header current)
1348		(rmail-mime-display-header new))
1349	    (goto-char (aref segment 2))
1350	  (if (rmail-mime-display-header current)
1351	      (delete-char (- (aref segment 2) (aref segment 1))))
1352	  (insert-buffer-substring rmail-mime-mbox-buffer
1353				   (aref header 0) (aref header 1)))
1354	;; tagline
1355	(if (rmail-mime-display-tagline current)
1356	    (delete-char (- (aref segment 3) (aref segment 2))))
1357	;; body
1358	(let ((children (rmail-mime-entity-children entity)))
1359	  (if children
1360	      (progn
1361		(put-text-property beg (point) 'rmail-mime-entity entity)
1362		(dolist (child children)
1363		  (rmail-mime-insert child)))
1364	    (if (eq (rmail-mime-display-body current)
1365		    (rmail-mime-display-body new))
1366		(forward-char (- (aref segment 4) (aref segment 3)))
1367	      (if (rmail-mime-display-body current)
1368		(delete-char (- (aref segment 4) (aref segment 3))))
1369	      (insert-buffer-substring rmail-mime-mbox-buffer
1370				       (aref body 0) (aref body 1))
1371	      (or (bolp) (insert "\n")))
1372	    (put-text-property beg (point) 'rmail-mime-entity entity)))))
1373    (dotimes (i 3)
1374      (aset current i (aref new i)))))
1375
1376(define-derived-mode rmail-mime-mode fundamental-mode "RMIME"
1377  "Major mode used in `rmail-mime' buffers."
1378  (setq font-lock-defaults '(rmail-font-lock-keywords t t nil nil)))
1379
1380;;;###autoload
1381(defun rmail-mime (&optional arg state)
1382  "Toggle the display of a MIME message.
1383
1384The actual behavior depends on the value of `rmail-enable-mime'.
1385
1386If `rmail-enable-mime' is non-nil (the default), this command toggles
1387the display of a MIME message between decoded presentation form and
1388raw data.  With optional prefix argument ARG, it toggles the display only
1389of the MIME entity at point, if there is one.  The optional argument
1390STATE forces a particular display state, rather than toggling.
1391`raw' forces raw mode, any other non-nil value forces decoded mode.
1392
1393If `rmail-enable-mime' is nil, this creates a temporary \"*RMAIL*\"
1394buffer holding a decoded copy of the message.  Inline content-types
1395are handled according to `rmail-mime-media-type-handlers-alist'.
1396By default, this displays text and multipart messages, and offers to
1397download attachments as specified by `rmail-mime-attachment-dirs-alist'.
1398The arguments ARG and STATE have no effect in this case."
1399  (interactive (list current-prefix-arg nil))
1400  (if rmail-enable-mime
1401      (with-current-buffer rmail-buffer
1402	(if (or (rmail-mime-message-p)
1403		(get-text-property (point-min) 'rmail-mime-hidden))
1404	    (let* ((hidden (get-text-property (point-min) 'rmail-mime-hidden))
1405		   (desired-hidden (if state (eq state 'raw) (not hidden))))
1406	      (unless (eq hidden desired-hidden)
1407		(if (not desired-hidden)
1408		    (rmail-show-message rmail-current-message)
1409		  (let ((rmail-enable-mime nil)
1410			(inhibit-read-only t))
1411		    (rmail-show-message rmail-current-message)
1412		    (add-text-properties (point-min) (point-max) '(rmail-mime-hidden t))))))
1413	  (message "Not a MIME message, just toggling headers")
1414	  (rmail-toggle-header)))
1415    (let* ((data (rmail-apply-in-message rmail-current-message 'buffer-string))
1416	   (buf (get-buffer-create "*RMAIL*"))
1417	   (rmail-mime-mbox-buffer rmail-view-buffer)
1418	   (rmail-mime-view-buffer buf))
1419      (set-buffer buf)
1420      (setq buffer-undo-list t)
1421      (let ((inhibit-read-only t))
1422	;; Decoding the message in fundamental mode for speed, only
1423	;; switching to rmail-mime-mode at the end for display.  Eg
1424	;; quoted-printable-decode-region gets very slow otherwise (Bug#4993).
1425	(fundamental-mode)
1426	(erase-buffer)
1427	(insert data)
1428	(rmail-mime-show t)
1429	(rmail-mime-mode)
1430	(set-buffer-modified-p nil))
1431      (view-buffer buf))))
1432
1433(defun rmail-mm-get-boundary-error-message (message type disposition encoding)
1434  "Return MESSAGE with more information on the main MIME components."
1435  (error "%s; type: %s; disposition: %s; encoding: %s"
1436	 message type disposition encoding))
1437
1438(defun rmail-show-mime ()
1439  "Function to use for the value of `rmail-show-mime-function'."
1440  (let ((entity (rmail-mime-parse))
1441	(rmail-mime-mbox-buffer rmail-buffer)
1442	(rmail-mime-view-buffer rmail-view-buffer)
1443	(rmail-mime-coding-system nil))
1444    ;; If ENTITY is not a vector, it is a string describing an error.
1445    (if (vectorp entity)
1446	(with-current-buffer rmail-mime-view-buffer
1447	  (erase-buffer)
1448	  ;; This condition-case is for catching an error in the
1449	  ;; internal MIME decoding (e.g. incorrect BASE64 form) that
1450	  ;; may be signaled by rmail-mime-insert.
1451	  ;; FIXME: The current code doesn't set a proper error symbol
1452	  ;; in ERR.  We must find a way to propagate a correct error
1453	  ;; symbol that is caused in the very deep code of text
1454	  ;; decoding (e.g. an error by base64-decode-region called by
1455	  ;; post-read-conversion function of utf-7).
1456	  (condition-case err
1457	      (progn
1458		(rmail-mime-insert entity)
1459		(if (consp rmail-mime-coding-system)
1460		    ;; Decoding is done by rfc2047-decode-region only for a
1461		    ;; header.  But, as the used coding system may have been
1462		    ;; overridden by mm-charset-override-alist, we can't
1463		    ;; trust (car rmail-mime-coding-system).  So, here we
1464		    ;; try the decoding again with mm-charset-override-alist
1465		    ;; bound to nil.
1466		    (let ((mm-charset-override-alist nil))
1467		      (setq rmail-mime-coding-system
1468			    (rmail-mime-find-header-encoding
1469			     (rmail-mime-entity-header entity)))))
1470		(set-buffer-file-coding-system
1471		 (if rmail-mime-coding-system
1472		     (coding-system-base rmail-mime-coding-system)
1473		   'undecided)
1474		 t t))
1475	    (error (setq entity (format "%s" err))))))
1476    ;; Re-check ENTITY.  It may be set to an error string.
1477    (when (stringp entity)
1478      ;; Decoding failed.  ENTITY is an error message.  Insert the
1479      ;; original message body as is, and show warning.
1480      (let ((region (with-current-buffer rmail-mime-mbox-buffer
1481		      (goto-char (point-min))
1482		      (re-search-forward "^$" nil t)
1483		      (forward-line 1)
1484		      (vector (point-min) (point) (point-max)))))
1485	(with-current-buffer rmail-mime-view-buffer
1486	  (let ((inhibit-read-only t))
1487	    (erase-buffer)
1488	    (rmail-mime-insert-header region)
1489	    (insert-buffer-substring rmail-mime-mbox-buffer
1490				     (aref region 1) (aref region 2))))
1491	(set-buffer-file-coding-system 'no-conversion t t)
1492	(message "MIME decoding failed: %s" entity)))))
1493
1494(setq rmail-show-mime-function 'rmail-show-mime)
1495
1496(defun rmail-insert-mime-forwarded-message (forward-buffer)
1497  "Insert the message in FORWARD-BUFFER as a forwarded message.
1498This is the usual value of `rmail-insert-mime-forwarded-message-function'."
1499  (let (contents-buffer start end)
1500    (with-current-buffer forward-buffer
1501      (setq contents-buffer
1502	    (if rmail-buffer-swapped
1503		rmail-view-buffer
1504	      forward-buffer)
1505	    start (rmail-msgbeg rmail-current-message)
1506	    end (rmail-msgend rmail-current-message)))
1507    (message-forward-make-body-mime contents-buffer start end)))
1508
1509(setq rmail-insert-mime-forwarded-message-function
1510      'rmail-insert-mime-forwarded-message)
1511
1512(defun rmail-insert-mime-resent-message (forward-buffer)
1513  "Function to set in `rmail-insert-mime-resent-message-function' (which see)."
1514  (insert-buffer-substring
1515   (with-current-buffer forward-buffer rmail-view-buffer))
1516  (goto-char (point-min))
1517  (when (looking-at "From ")
1518    (forward-line 1)
1519    (delete-region (point-min) (point))))
1520
1521(setq rmail-insert-mime-resent-message-function
1522      'rmail-insert-mime-resent-message)
1523
1524(defun rmail-search-mime-message (msg regexp)
1525  "Function to set in `rmail-search-mime-message-function' (which see)."
1526  (save-restriction
1527    (narrow-to-region (rmail-msgbeg msg) (rmail-msgend msg))
1528    (let* ((rmail-mime-searching t)	; mark inside search
1529	   (rmail-mime-mbox-buffer (current-buffer))
1530	   (rmail-mime-view-buffer rmail-view-buffer)
1531	   (header-end (save-excursion
1532			 (re-search-forward "^$" nil 'move) (point)))
1533	   (body-end (point-max))
1534	   (entity (rmail-mime-parse)))
1535      (or
1536       ;; At first, just search the headers.
1537       (with-temp-buffer
1538	 (insert-buffer-substring rmail-mime-mbox-buffer nil header-end)
1539	 (rfc2047-decode-region (point-min) (point))
1540	 (goto-char (point-min))
1541	 (re-search-forward regexp nil t))
1542       ;; Next, search the body.
1543       (if (and entity
1544		;; RMS: I am not sure why, but sometimes this is a string.
1545		(not (stringp entity))
1546		(let* ((content-type (rmail-mime-entity-type entity))
1547		       (charset (cdr (assq 'charset (cdr content-type)))))
1548		  (or (not (string-match "text/.*" (car content-type)))
1549		      (and charset
1550			   (not (string= (downcase charset) "us-ascii"))))))
1551	   ;; Search the decoded MIME message.
1552	   (with-temp-buffer
1553	     (rmail-mime-insert entity)
1554	     (goto-char (point-min))
1555	     (re-search-forward regexp nil t))
1556	 ;; Search the body without decoding.
1557	 (goto-char header-end)
1558	 (re-search-forward regexp nil t))))))
1559
1560(setq rmail-search-mime-message-function 'rmail-search-mime-message)
1561
1562(provide 'rmailmm)
1563
1564;; Local Variables:
1565;; generated-autoload-file: "rmail-loaddefs.el"
1566;; End:
1567
1568;;; rmailmm.el ends here
1569