2949b1c6d863230e35538261d1d4fe90df22c942
[gnus] / lisp / mm-decode.el
1 ;;; mm-decode.el --- Functions for decoding MIME things
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'mail-parse)
28 (require 'mailcap)
29 (require 'mm-bodies)
30 (eval-when-compile (require 'cl)
31                    (require 'term))
32
33 (eval-and-compile
34   (autoload 'executable-find "executable")
35   (autoload 'mm-inline-partial "mm-partial")
36   (autoload 'mm-inline-external-body "mm-extern")
37   (autoload 'mm-insert-inline "mm-view"))
38
39 (add-hook 'gnus-exit-gnus-hook 'mm-destroy-postponed-undisplay-list)
40
41 (defgroup mime-display ()
42   "Display of MIME in mail and news articles."
43   :link '(custom-manual "(emacs-mime)Customization")
44   :version "21.1"
45   :group 'mail
46   :group 'news
47   :group 'multimedia)
48
49 (defgroup mime-security ()
50   "MIME security in mail and news articles."
51   :link '(custom-manual "(emacs-mime)Customization")
52   :group 'mail
53   :group 'news
54   :group 'multimedia)
55
56 ;;; Convenience macros.
57
58 (defmacro mm-handle-buffer (handle)
59   `(nth 0 ,handle))
60 (defmacro mm-handle-type (handle)
61   `(nth 1 ,handle))
62 (defsubst mm-handle-media-type (handle)
63   (if (stringp (car handle))
64       (car handle)
65     (car (mm-handle-type handle))))
66 (defsubst mm-handle-media-supertype (handle)
67   (car (split-string (mm-handle-media-type handle) "/")))
68 (defsubst mm-handle-media-subtype (handle)
69   (cadr (split-string (mm-handle-media-type handle) "/")))
70 (defmacro mm-handle-encoding (handle)
71   `(nth 2 ,handle))
72 (defmacro mm-handle-undisplayer (handle)
73   `(nth 3 ,handle))
74 (defmacro mm-handle-set-undisplayer (handle function)
75   `(setcar (nthcdr 3 ,handle) ,function))
76 (defmacro mm-handle-disposition (handle)
77   `(nth 4 ,handle))
78 (defmacro mm-handle-description (handle)
79   `(nth 5 ,handle))
80 (defmacro mm-handle-cache (handle)
81   `(nth 6 ,handle))
82 (defmacro mm-handle-set-cache (handle contents)
83   `(setcar (nthcdr 6 ,handle) ,contents))
84 (defmacro mm-handle-id (handle)
85   `(nth 7 ,handle))
86 (defmacro mm-handle-multipart-original-buffer (handle)
87   `(get-text-property 0 'buffer (car ,handle)))
88 (defmacro mm-handle-multipart-from (handle)
89   `(get-text-property 0 'from (car ,handle)))
90 (defmacro mm-handle-multipart-ctl-parameter (handle parameter)
91   `(get-text-property 0 ,parameter (car ,handle)))
92
93 (defmacro mm-make-handle (&optional buffer type encoding undisplayer
94                                     disposition description cache
95                                     id)
96   `(list ,buffer ,type ,encoding ,undisplayer
97          ,disposition ,description ,cache ,id))
98
99 (defcustom mm-text-html-renderer
100   (cond ((locate-library "w3") 'w3)
101         ((locate-library "w3m") 'w3m)
102         ((executable-find "links") 'links)
103         ((executable-find "lynx") 'lynx))
104   "Render of HTML contents.
105 It is one of defined renderer types, or a rendering function.
106 The defined renderer types are:
107 `w3'   : using Emacs/W3;
108 `w3m'  : using emacs-w3m;
109 `links': using links;
110 `lynx' : using lynx;
111 `nil'  : using external viewer."
112   :type '(choice (symbol w3)
113                  (symbol w3m)
114                  (symbol links)
115                  (symbol lynx)
116                  (symbol nil)
117                  (function))
118   :version "21.3"
119   :group 'mime-display)
120
121 (defvar mm-inline-text-html-renderer nil
122   "Function used for rendering inline HTML contents.
123 It is suggested to customize `mm-text-html-renderer' instead.")
124
125 (defcustom mm-inline-text-html-with-images nil
126   "If non-nil, Gnus will allow retrieving images in the HTML contents
127 with <img> tags.  It has no effect on Emacs/w3.  For emacs-w3m, the
128 value of the option `w3m-display-inline-images' will be bound with
129 this value.  In addition, the variable `w3m-safe-url-regexp' will be
130 bound with the value nil if it is non-nil to make emacs-w3m show all
131 images, however this behavior may be changed in the future."
132   :type 'boolean
133   :group 'mime-display)
134
135 (defcustom mm-inline-text-html-with-w3m-keymap t
136   "If non-nil, use emacs-w3m command keys in the article buffer."
137   :type 'boolean
138   :group 'mime-display)
139
140 (defcustom mm-inline-media-tests
141   '(("image/jpeg"
142      mm-inline-image
143      (lambda (handle)
144        (mm-valid-and-fit-image-p 'jpeg handle)))
145     ("image/png"
146      mm-inline-image
147      (lambda (handle)
148        (mm-valid-and-fit-image-p 'png handle)))
149     ("image/gif"
150      mm-inline-image
151      (lambda (handle)
152        (mm-valid-and-fit-image-p 'gif handle)))
153     ("image/tiff"
154      mm-inline-image
155      (lambda (handle)
156        (mm-valid-and-fit-image-p 'tiff handle)) )
157     ("image/xbm"
158      mm-inline-image
159      (lambda (handle)
160        (mm-valid-and-fit-image-p 'xbm handle)))
161     ("image/x-xbitmap"
162      mm-inline-image
163      (lambda (handle)
164        (mm-valid-and-fit-image-p 'xbm handle)))
165     ("image/xpm"
166      mm-inline-image
167      (lambda (handle)
168        (mm-valid-and-fit-image-p 'xpm handle)))
169     ("image/x-pixmap"
170      mm-inline-image
171      (lambda (handle)
172        (mm-valid-and-fit-image-p 'xpm handle)))
173     ("image/bmp"
174      mm-inline-image
175      (lambda (handle)
176        (mm-valid-and-fit-image-p 'bmp handle)))
177     ("image/x-portable-bitmap"
178      mm-inline-image
179      (lambda (handle)
180        (mm-valid-and-fit-image-p 'pbm handle)))
181     ("text/plain" mm-inline-text identity)
182     ("text/enriched" mm-inline-text identity)
183     ("text/richtext" mm-inline-text identity)
184     ("text/x-patch" mm-display-patch-inline
185      (lambda (handle)
186        (locate-library "diff-mode")))
187     ("application/emacs-lisp" mm-display-elisp-inline identity)
188     ("application/x-emacs-lisp" mm-display-elisp-inline identity)
189     ("text/html"
190      mm-inline-text-html
191      (lambda (handle)
192        (or mm-inline-text-html-renderer
193            mm-text-html-renderer)))
194     ("text/x-vcard"
195      mm-inline-text-vcard
196      (lambda (handle)
197        (or (featurep 'vcard)
198            (locate-library "vcard"))))
199     ("message/delivery-status" mm-inline-text identity)
200     ("message/rfc822" mm-inline-message identity)
201     ("message/partial" mm-inline-partial identity)
202     ("message/external-body" mm-inline-external-body identity)
203     ("text/.*" mm-inline-text identity)
204     ("audio/wav" mm-inline-audio
205      (lambda (handle)
206        (and (or (featurep 'nas-sound) (featurep 'native-sound))
207             (device-sound-enabled-p))))
208     ("audio/au"
209      mm-inline-audio
210      (lambda (handle)
211        (and (or (featurep 'nas-sound) (featurep 'native-sound))
212             (device-sound-enabled-p))))
213     ("application/pgp-signature" ignore identity)
214     ("application/x-pkcs7-signature" ignore identity)
215     ("application/pkcs7-signature" ignore identity)
216     ("application/x-pkcs7-mime" ignore identity)
217     ("application/pkcs7-mime" ignore identity)
218     ("multipart/alternative" ignore identity)
219     ("multipart/mixed" ignore identity)
220     ("multipart/related" ignore identity)
221     ;; Disable audio and image
222     ("audio/.*" ignore ignore)
223     ("image/.*" ignore ignore)
224     ;; Default to displaying as text
225     (".*" mm-inline-text mm-readable-p))
226   "Alist of media types/tests saying whether types can be displayed inline."
227   :type '(repeat (list (string :tag "MIME type")
228                        (function :tag "Display function")
229                        (function :tag "Display test")))
230   :group 'mime-display)
231
232 (defcustom mm-inlined-types
233   '("image/.*" "text/.*" "message/delivery-status" "message/rfc822"
234     "message/partial" "message/external-body" "application/emacs-lisp"
235     "application/pgp-signature" "application/x-pkcs7-signature"
236     "application/pkcs7-signature" "application/x-pkcs7-mime"
237     "application/pkcs7-mime")
238   "List of media types that are to be displayed inline.
239 See also `mm-inline-media-tests', which says how to display a media
240 type inline."
241   :type '(repeat string)
242   :group 'mime-display)
243
244 (defcustom mm-keep-viewer-alive-types
245   '("application/postscript" "application/msword" "application/vnd.ms-excel"
246     "application/pdf" "application/x-dvi")
247   "List of media types for which the external viewer will not be killed
248 when selecting a different article."
249   :type '(repeat string)
250   :group 'mime-display)
251
252 (defcustom mm-automatic-display
253   '("text/plain" "text/enriched" "text/richtext" "text/html"
254     "text/x-vcard" "image/.*" "message/delivery-status" "multipart/.*"
255     "message/rfc822" "text/x-patch" "application/pgp-signature"
256     "application/emacs-lisp" "application/x-pkcs7-signature"
257     "application/pkcs7-signature" "application/x-pkcs7-mime"
258     "application/pkcs7-mime")
259   "A list of MIME types to be displayed automatically."
260   :type '(repeat string)
261   :group 'mime-display)
262
263 (defcustom mm-attachment-override-types '("text/x-vcard"
264                                           "application/pkcs7-mime"
265                                           "application/x-pkcs7-mime"
266                                           "application/pkcs7-signature"
267                                           "application/x-pkcs7-signature")
268   "Types to have \"attachment\" ignored if they can be displayed inline."
269   :type '(repeat string)
270   :group 'mime-display)
271
272 (defcustom mm-inline-override-types nil
273   "Types to be treated as attachments even if they can be displayed inline."
274   :type '(repeat string)
275   :group 'mime-display)
276
277 (defcustom mm-automatic-external-display nil
278   "List of MIME type regexps that will be displayed externally automatically."
279   :type '(repeat string)
280   :group 'mime-display)
281
282 (defcustom mm-discouraged-alternatives nil
283   "List of MIME types that are discouraged when viewing multipart/alternative.
284 Viewing agents are supposed to view the last possible part of a message,
285 as that is supposed to be the richest.  However, users may prefer other
286 types instead, and this list says what types are most unwanted.  If,
287 for instance, text/html parts are very unwanted, and text/richtext are
288 somewhat unwanted, then the value of this variable should be set
289 to:
290
291  (\"text/html\" \"text/richtext\")"
292   :type '(repeat string)
293   :group 'mime-display)
294
295 (defcustom mm-tmp-directory
296   (cond ((fboundp 'temp-directory) (temp-directory))
297         ((boundp 'temporary-file-directory) temporary-file-directory)
298         ("/tmp/"))
299   "Where mm will store its temporary files."
300   :type 'directory
301   :group 'mime-display)
302
303 (defcustom mm-inline-large-images nil
304   "If non-nil, then all images fit in the buffer."
305   :type 'boolean
306   :group 'mime-display)
307
308 (defvar mm-file-name-rewrite-functions nil
309   "*List of functions used for rewriting file names of MIME parts.
310 Each function takes a file name as input and returns a file name.
311
312 Ready-made functions include
313 `mm-file-name-delete-whitespace',
314 `mm-file-name-trim-whitespace',
315 `mm-file-name-collapse-whitespace',
316 `mm-file-name-replace-whitespace',
317 `capitalize', `downcase', `upcase', and
318 `upcase-initials'.")
319
320 (defvar mm-path-name-rewrite-functions nil
321   "*List of functions used for rewriting path names of MIME parts.
322 This is used when viewing parts externally , and is meant for
323 transforming the path name so that non-compliant programs can
324 find the file where it's saved.
325
326 Each function takes a file name as input and returns a file name.")
327
328 (defvar mm-file-name-replace-whitespace nil
329   "String used for replacing whitespace characters; default is `\"_\"'.")
330
331 (defcustom mm-default-directory nil
332   "The default directory where mm will save files.
333 If not set, `default-directory' will be used."
334   :type '(choice directory (const :tag "Default" nil))
335   :group 'mime-display)
336
337 (defcustom mm-external-terminal-program "xterm"
338   "The program to start an external terminal."
339   :type 'string
340   :group 'mime-display)
341
342 ;;; Internal variables.
343
344 (defvar mm-dissection-list nil)
345 (defvar mm-last-shell-command "")
346 (defvar mm-content-id-alist nil)
347 (defvar mm-postponed-undisplay-list nil)
348
349 ;; According to RFC2046, in particular, in a digest, the default
350 ;; Content-Type value for a body part is changed from "text/plain" to
351 ;; "message/rfc822".
352 (defvar mm-dissect-default-type "text/plain")
353
354 (autoload 'mml2015-verify "mml2015")
355 (autoload 'mml2015-verify-test "mml2015")
356 (autoload 'mml-smime-verify "mml-smime")
357 (autoload 'mml-smime-verify-test "mml-smime")
358
359 (defvar mm-verify-function-alist
360   '(("application/pgp-signature" mml2015-verify "PGP" mml2015-verify-test)
361     ("application/x-gnus-pgp-signature" mm-uu-pgp-signed-extract-1 "PGP"
362      mm-uu-pgp-signed-test)
363     ("application/pkcs7-signature" mml-smime-verify "S/MIME"
364      mml-smime-verify-test)
365     ("application/x-pkcs7-signature" mml-smime-verify "S/MIME"
366      mml-smime-verify-test)))
367
368 (defcustom mm-verify-option 'never
369   "Option of verifying signed parts.
370 `never', not verify; `always', always verify;
371 `known', only verify known protocols. Otherwise, ask user."
372   :type '(choice (item always)
373                  (item never)
374                  (item :tag "only known protocols" known)
375                  (item :tag "ask" nil))
376   :group 'mime-security)
377
378 (autoload 'mml2015-decrypt "mml2015")
379 (autoload 'mml2015-decrypt-test "mml2015")
380
381 (defvar mm-decrypt-function-alist
382   '(("application/pgp-encrypted" mml2015-decrypt "PGP" mml2015-decrypt-test)
383     ("application/x-gnus-pgp-encrypted" mm-uu-pgp-encrypted-extract-1 "PGP"
384      mm-uu-pgp-encrypted-test)))
385
386 (defcustom mm-decrypt-option nil
387   "Option of decrypting encrypted parts.
388 `never', not decrypt; `always', always decrypt;
389 `known', only decrypt known protocols. Otherwise, ask user."
390   :type '(choice (item always)
391                  (item never)
392                  (item :tag "only known protocols" known)
393                  (item :tag "ask" nil))
394   :group 'mime-security)
395
396 (defvar mm-viewer-completion-map
397   (let ((map (make-sparse-keymap 'mm-viewer-completion-map)))
398     (set-keymap-parent map minibuffer-local-completion-map)
399     map)
400   "Keymap for input viewer with completion.")
401
402 ;; Should we bind other key to minibuffer-complete-word?
403 (define-key mm-viewer-completion-map " " 'self-insert-command)
404
405 (defvar mm-viewer-completion-map
406   (let ((map (make-sparse-keymap 'mm-viewer-completion-map)))
407     (set-keymap-parent map minibuffer-local-completion-map)
408     map)
409   "Keymap for input viewer with completion.")
410
411 ;; Should we bind other key to minibuffer-complete-word?
412 (define-key mm-viewer-completion-map " " 'self-insert-command)
413
414 ;;; The functions.
415
416 (defun mm-alist-to-plist (alist)
417   "Convert association list ALIST into the equivalent property-list form.
418 The plist is returned.  This converts from
419
420 \((a . 1) (b . 2) (c . 3))
421
422 into
423
424 \(a 1 b 2 c 3)
425
426 The original alist is not modified.  See also `destructive-alist-to-plist'."
427   (let (plist)
428     (while alist
429       (let ((el (car alist)))
430         (setq plist (cons (cdr el) (cons (car el) plist))))
431       (setq alist (cdr alist)))
432     (nreverse plist)))
433
434 (defun mm-keep-viewer-alive-p (handle)
435   "Say whether external viewer for HANDLE should stay alive."
436   (let ((types mm-keep-viewer-alive-types)
437         (type (mm-handle-media-type handle))
438         ty)
439     (catch 'found
440       (while (setq ty (pop types))
441         (when (string-match ty type)
442           (throw 'found t))))))
443
444 (defun mm-handle-set-external-undisplayer (handle function)
445   "Set the undisplayer for this handle; postpone undisplaying of viewers
446 for types in mm-keep-viewer-alive-types."
447   (if (mm-keep-viewer-alive-p handle)
448       (let ((new-handle (copy-sequence handle)))
449         (mm-handle-set-undisplayer new-handle function)
450         (mm-handle-set-undisplayer handle nil)
451         (push new-handle mm-postponed-undisplay-list))
452     (mm-handle-set-undisplayer handle function)))
453
454 (defun mm-destroy-postponed-undisplay-list ()
455   (when mm-postponed-undisplay-list
456     (message "Destroying external MIME viewers")
457     (mm-destroy-parts mm-postponed-undisplay-list)))
458
459 (defun mm-dissect-buffer (&optional no-strict-mime loose-mime)
460   "Dissect the current buffer and return a list of MIME handles."
461   (save-excursion
462     (let (ct ctl type subtype cte cd description id result from)
463       (save-restriction
464         (mail-narrow-to-head)
465         (when (or no-strict-mime
466                   loose-mime
467                   (mail-fetch-field "mime-version"))
468           (setq ct (mail-fetch-field "content-type")
469                 ctl (ignore-errors (mail-header-parse-content-type ct))
470                 cte (mail-fetch-field "content-transfer-encoding")
471                 cd (mail-fetch-field "content-disposition")
472                 description (mail-fetch-field "content-description")
473                 from (mail-fetch-field "from")
474                 id (mail-fetch-field "content-id"))
475           ;; FIXME: In some circumstances, this code is running within
476           ;; an unibyte macro.  mail-extract-address-components
477           ;; creates unibyte buffers. This `if', though not a perfect
478           ;; solution, avoids most of them.
479           (if from
480               (setq from (cadr (mail-extract-address-components from))))))
481       (when cte
482         (setq cte (mail-header-strip cte)))
483       (if (or (not ctl)
484               (not (string-match "/" (car ctl))))
485           (mm-dissect-singlepart
486            (list mm-dissect-default-type)
487            (and cte (intern (downcase (mail-header-remove-whitespace
488                                        (mail-header-remove-comments
489                                         cte)))))
490            no-strict-mime
491            (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
492            description)
493         (setq type (split-string (car ctl) "/"))
494         (setq subtype (cadr type)
495               type (pop type))
496         (setq
497          result
498          (cond
499           ((equal type "multipart")
500            (let ((mm-dissect-default-type (if (equal subtype "digest")
501                                               "message/rfc822"
502                                             "text/plain")))
503              (add-text-properties 0 (length (car ctl))
504                                   (mm-alist-to-plist (cdr ctl)) (car ctl))
505
506              ;; what really needs to be done here is a way to link a
507              ;; MIME handle back to it's parent MIME handle (in a multilevel
508              ;; MIME article).  That would probably require changing
509              ;; the mm-handle API so we simply store the multipart buffert
510              ;; name as a text property of the "multipart/whatever" string.
511              (add-text-properties 0 (length (car ctl))
512                                   (list 'buffer (mm-copy-to-buffer))
513                                   (car ctl))
514              (add-text-properties 0 (length (car ctl))
515                                   (list 'from from)
516                                   (car ctl))
517              (cons (car ctl) (mm-dissect-multipart ctl))))
518           (t
519            (mm-possibly-verify-or-decrypt
520             (mm-dissect-singlepart
521              ctl
522              (and cte (intern (downcase (mail-header-remove-whitespace
523                                          (mail-header-remove-comments
524                                           cte)))))
525              no-strict-mime
526              (and cd (ignore-errors
527                        (mail-header-parse-content-disposition cd)))
528              description id)
529             ctl))))
530         (when id
531           (when (string-match " *<\\(.*\\)> *" id)
532             (setq id (match-string 1 id)))
533           (push (cons id result) mm-content-id-alist))
534         result))))
535
536 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
537   (when (or force
538             (if (equal "text/plain" (car ctl))
539                 (assoc 'format ctl)
540               t))
541     (let ((res (mm-make-handle
542                 (mm-copy-to-buffer) ctl cte nil cdl description nil id)))
543       (push (car res) mm-dissection-list)
544       res)))
545
546 (defun mm-remove-all-parts ()
547   "Remove all MIME handles."
548   (interactive)
549   (mapcar 'mm-remove-part mm-dissection-list)
550   (setq mm-dissection-list nil))
551
552 (defun mm-dissect-multipart (ctl)
553   (goto-char (point-min))
554   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
555          (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
556          start parts
557          (end (save-excursion
558                 (goto-char (point-max))
559                 (if (re-search-backward close-delimiter nil t)
560                     (match-beginning 0)
561                   (point-max)))))
562     (setq boundary (concat (regexp-quote boundary) "[ \t]*$"))
563     (while (and (< (point) end) (re-search-forward boundary end t))
564       (goto-char (match-beginning 0))
565       (when start
566         (save-excursion
567           (save-restriction
568             (narrow-to-region start (point))
569             (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
570       (end-of-line 2)
571       (or (looking-at boundary)
572           (forward-line 1))
573       (setq start (point)))
574     (when (and start (< start end))
575       (save-excursion
576         (save-restriction
577           (narrow-to-region start end)
578           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
579     (mm-possibly-verify-or-decrypt (nreverse parts) ctl)))
580
581 (defun mm-copy-to-buffer ()
582   "Copy the contents of the current buffer to a fresh buffer."
583   (save-excursion
584     (let ((obuf (current-buffer))
585           beg)
586       (goto-char (point-min))
587       (search-forward-regexp "^\n" nil t)
588       (setq beg (point))
589       (set-buffer (generate-new-buffer " *mm*"))
590       (insert-buffer-substring obuf beg)
591       (current-buffer))))
592
593 (defun mm-display-parts (handle &optional no-default)
594   (if (stringp (car handle))
595       (mapcar 'mm-display-parts (cdr handle))
596     (if (bufferp (car handle))
597         (save-restriction
598           (narrow-to-region (point) (point))
599           (mm-display-part handle)
600           (goto-char (point-max)))
601       (mapcar 'mm-display-parts handle))))
602
603 (defun mm-display-part (handle &optional no-default)
604   "Display the MIME part represented by HANDLE.
605 Returns nil if the part is removed; inline if displayed inline;
606 external if displayed external."
607   (save-excursion
608     (mailcap-parse-mailcaps)
609     (if (mm-handle-displayed-p handle)
610         (mm-remove-part handle)
611       (let* ((type (mm-handle-media-type handle))
612              (method (mailcap-mime-info type)))
613         (if (and (mm-inlinable-p handle)
614                  (mm-inlined-p handle))
615             (progn
616               (forward-line 1)
617               (mm-display-inline handle)
618               'inline)
619           (when (or method
620                     (not no-default))
621             (if (and (not method)
622                      (equal "text" (car (split-string type))))
623                 (progn
624                   (forward-line 1)
625                   (mm-insert-inline handle (mm-get-part handle))
626                   'inline)
627               (mm-display-external
628                handle (or method 'mailcap-save-binary-file)))))))))
629
630 (defun mm-display-external (handle method)
631   "Display HANDLE using METHOD."
632   (let ((outbuf (current-buffer)))
633     (mm-with-unibyte-buffer
634       (if (functionp method)
635           (let ((cur (current-buffer)))
636             (if (eq method 'mailcap-save-binary-file)
637                 (progn
638                   (set-buffer (generate-new-buffer " *mm*"))
639                   (setq method nil))
640               (mm-insert-part handle)
641               (let ((win (get-buffer-window cur t)))
642                 (when win
643                   (select-window win)))
644               (switch-to-buffer (generate-new-buffer " *mm*")))
645             (buffer-disable-undo)
646             (mm-set-buffer-file-coding-system mm-binary-coding-system)
647             (insert-buffer-substring cur)
648             (goto-char (point-min))
649             (message "Viewing with %s" method)
650             (let ((mm (current-buffer))
651                   (non-viewer (assq 'non-viewer
652                                     (mailcap-mime-info
653                                      (mm-handle-media-type handle) t))))
654               (unwind-protect
655                   (if method
656                       (funcall method)
657                     (mm-save-part handle))
658                 (when (and (not non-viewer)
659                            method)
660                   (mm-handle-set-undisplayer handle mm)))))
661         ;; The function is a string to be executed.
662         (mm-insert-part handle)
663         (let* ((dir (make-temp-name
664                      (expand-file-name "emm." mm-tmp-directory)))
665                (filename (or 
666                           (mail-content-type-get
667                            (mm-handle-disposition handle) 'filename)
668                           (mail-content-type-get
669                            (mm-handle-type handle) 'name)))
670                (mime-info (mailcap-mime-info
671                            (mm-handle-media-type handle) t))
672                (needsterm (or (assoc "needsterm" mime-info)
673                               (assoc "needsterminal" mime-info)))
674                (copiousoutput (assoc "copiousoutput" mime-info))
675                file buffer)
676           ;; We create a private sub-directory where we store our files.
677           (make-directory dir)
678           (set-file-modes dir 448)
679           (if filename
680               (setq file (expand-file-name (file-name-nondirectory filename)
681                                            dir))
682             (setq file (make-temp-name (expand-file-name "mm." dir))))
683           (let ((coding-system-for-write mm-binary-coding-system))
684             (write-region (point-min) (point-max) file nil 'nomesg))
685           (message "Viewing with %s" method)
686           (cond
687            (needsterm
688             (unwind-protect
689                 (if window-system
690                     (start-process "*display*" nil
691                                    mm-external-terminal-program
692                                    "-e" shell-file-name
693                                    shell-command-switch
694                                    (mm-mailcap-command
695                                     method file (mm-handle-type handle)))
696                   (require 'term)
697                   (require 'gnus-win)
698                   (set-buffer
699                    (setq buffer
700                          (make-term "display"
701                                     shell-file-name
702                                     nil
703                                     shell-command-switch
704                                     (mm-mailcap-command
705                                      method file
706                                      (mm-handle-type handle)))))
707                   (term-mode)
708                   (term-char-mode)
709                   (set-process-sentinel
710                    (get-buffer-process buffer)
711                    `(lambda (process state)
712                       (if (eq 'exit (process-status process))
713                           (gnus-configure-windows
714                            ',gnus-current-window-configuration))))
715                   (gnus-configure-windows 'display-term))
716               (mm-handle-set-external-undisplayer handle (cons file buffer)))
717             (message "Displaying %s..." (format method file))
718             'external)
719            (copiousoutput
720             (with-current-buffer outbuf
721               (forward-line 1)
722               (mm-insert-inline
723                handle
724                (unwind-protect
725                    (progn
726                      (call-process shell-file-name nil
727                                    (setq buffer
728                                          (generate-new-buffer " *mm*"))
729                                    nil
730                                    shell-command-switch
731                                    (mm-mailcap-command
732                                     method file (mm-handle-type handle)))
733                      (if (buffer-live-p buffer)
734                          (save-excursion
735                            (set-buffer buffer)
736                            (buffer-string))))
737                  (progn
738                    (ignore-errors (delete-file file))
739                    (ignore-errors (delete-directory
740                                    (file-name-directory file)))
741                    (ignore-errors (kill-buffer buffer))))))
742             'inline)
743            (t
744             (unwind-protect
745                 (start-process "*display*"
746                                (setq buffer
747                                      (generate-new-buffer " *mm*"))
748                                shell-file-name
749                                shell-command-switch
750                                (mm-mailcap-command
751                                 method file (mm-handle-type handle)))
752               (mm-handle-set-external-undisplayer
753                handle (cons file buffer)))
754             (message "Displaying %s..." (format method file))
755             'external)))))))
756
757 (defun mm-mailcap-command (method file type-list)
758   (let ((ctl (cdr type-list))
759         (beg 0)
760         (uses-stdin t)
761         out sub total)
762     (while (string-match "%{\\([^}]+\\)}\\|%s\\|%t\\|%%" method beg)
763       (push (substring method beg (match-beginning 0)) out)
764       (setq beg (match-end 0)
765             total (match-string 0 method)
766             sub (match-string 1 method))
767       (cond
768        ((string= total "%%")
769         (push "%" out))
770        ((string= total "%s")
771         (setq uses-stdin nil)
772         (push (mm-quote-arg
773                (gnus-map-function mm-path-name-rewrite-functions file)) out))
774        ((string= total "%t")
775         (push (mm-quote-arg (car type-list)) out))
776        (t
777         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
778     (push (substring method beg (length method)) out)
779     (when uses-stdin
780       (push "<" out)
781       (push (mm-quote-arg
782              (gnus-map-function mm-path-name-rewrite-functions file))
783             out))
784     (mapconcat 'identity (nreverse out) "")))
785
786 (defun mm-remove-parts (handles)
787   "Remove the displayed MIME parts represented by HANDLES."
788   (if (and (listp handles)
789            (bufferp (car handles)))
790       (mm-remove-part handles)
791     (let (handle)
792       (while (setq handle (pop handles))
793         (cond
794          ((stringp handle)
795           (when (buffer-live-p (get-text-property 0 'buffer handle))
796             (kill-buffer (get-text-property 0 'buffer handle))))
797          ((and (listp handle)
798                (stringp (car handle)))
799           (mm-remove-parts (cdr handle)))
800          (t
801           (mm-remove-part handle)))))))
802
803 (defun mm-destroy-parts (handles)
804   "Remove the displayed MIME parts represented by HANDLES."
805   (if (and (listp handles)
806            (bufferp (car handles)))
807       (mm-destroy-part handles)
808     (let (handle)
809       (while (setq handle (pop handles))
810         (cond
811          ((stringp handle)
812           (when (buffer-live-p (get-text-property 0 'buffer handle))
813             (kill-buffer (get-text-property 0 'buffer handle))))
814          ((and (listp handle)
815                (stringp (car handle)))
816           (mm-destroy-parts handle))
817          (t
818           (mm-destroy-part handle)))))))
819
820 (defun mm-remove-part (handle)
821   "Remove the displayed MIME part represented by HANDLE."
822   (when (listp handle)
823     (let ((object (mm-handle-undisplayer handle)))
824       (ignore-errors
825         (cond
826          ;; Internally displayed part.
827          ((mm-annotationp object)
828           (delete-annotation object))
829          ((or (functionp object)
830               (and (listp object)
831                    (eq (car object) 'lambda)))
832           (funcall object))
833          ;; Externally displayed part.
834          ((consp object)
835           (ignore-errors (delete-file (car object)))
836           (ignore-errors (delete-directory (file-name-directory (car object))))
837           (ignore-errors (and (cdr object) (kill-buffer (cdr object)))))
838          ((bufferp object)
839           (when (buffer-live-p object)
840             (kill-buffer object)))))
841       (mm-handle-set-undisplayer handle nil))))
842
843 (defun mm-display-inline (handle)
844   (let* ((type (mm-handle-media-type handle))
845          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
846     (funcall function handle)
847     (goto-char (point-min))))
848
849 (defun mm-assoc-string-match (alist type)
850   (dolist (elem alist)
851     (when (string-match (car elem) type)
852       (return elem))))
853
854 (defun mm-automatic-display-p (handle)
855   "Say whether the user wants HANDLE to be displayed automatically."
856   (let ((methods mm-automatic-display)
857         (type (mm-handle-media-type handle))
858         method result)
859     (while (setq method (pop methods))
860       (when (and (not (mm-inline-override-p handle))
861                  (string-match method type))
862         (setq result t
863               methods nil)))
864     result))
865
866 (defun mm-inlinable-p (handle)
867   "Say whether HANDLE can be displayed inline."
868   (let ((alist mm-inline-media-tests)
869         (type (mm-handle-media-type handle))
870         test)
871     (while alist
872       (when (string-match (caar alist) type)
873         (setq test (caddar alist)
874               alist nil)
875         (setq test (funcall test handle)))
876       (pop alist))
877     test))
878
879 (defun mm-inlined-p (handle)
880   "Say whether the user wants HANDLE to be displayed inline."
881   (let ((methods mm-inlined-types)
882         (type (mm-handle-media-type handle))
883         method result)
884     (while (setq method (pop methods))
885       (when (and (not (mm-inline-override-p handle))
886                  (string-match method type))
887         (setq result t
888               methods nil)))
889     result))
890
891 (defun mm-attachment-override-p (handle)
892   "Say whether HANDLE should have attachment behavior overridden."
893   (let ((types mm-attachment-override-types)
894         (type (mm-handle-media-type handle))
895         ty)
896     (catch 'found
897       (while (setq ty (pop types))
898         (when (and (string-match ty type)
899                    (mm-inlinable-p handle))
900           (throw 'found t))))))
901
902 (defun mm-inline-override-p (handle)
903   "Say whether HANDLE should have inline behavior overridden."
904   (let ((types mm-inline-override-types)
905         (type (mm-handle-media-type handle))
906         ty)
907     (catch 'found
908       (while (setq ty (pop types))
909         (when (string-match ty type)
910           (throw 'found t))))))
911
912 (defun mm-automatic-external-display-p (type)
913   "Return the user-defined method for TYPE."
914   (let ((methods mm-automatic-external-display)
915         method result)
916     (while (setq method (pop methods))
917       (when (string-match method type)
918         (setq result t
919               methods nil)))
920     result))
921
922 (defun mm-destroy-part (handle)
923   "Destroy the data structures connected to HANDLE."
924   (when (listp handle)
925     (mm-remove-part handle)
926     (when (buffer-live-p (mm-handle-buffer handle))
927       (kill-buffer (mm-handle-buffer handle)))))
928
929 (defun mm-handle-displayed-p (handle)
930   "Say whether HANDLE is displayed or not."
931   (mm-handle-undisplayer handle))
932
933 ;;;
934 ;;; Functions for outputting parts
935 ;;;
936
937 (defun mm-get-part (handle)
938   "Return the contents of HANDLE as a string."
939   (mm-with-unibyte-buffer
940     (insert (with-current-buffer (mm-handle-buffer handle)
941               (mm-with-unibyte-current-buffer-mule4
942                 (buffer-string))))
943     (mm-decode-content-transfer-encoding
944      (mm-handle-encoding handle)
945      (mm-handle-media-type handle))
946     (buffer-string)))
947
948 (defun mm-insert-part (handle)
949   "Insert the contents of HANDLE in the current buffer."
950   (let ((cur (current-buffer)))
951     (save-excursion
952       (if (member (mm-handle-media-supertype handle) '("text" "message"))
953           (with-temp-buffer
954             (insert-buffer-substring (mm-handle-buffer handle))
955             (prog1
956                 (mm-decode-content-transfer-encoding
957                  (mm-handle-encoding handle)
958                  (mm-handle-media-type handle))
959               (let ((temp (current-buffer)))
960                 (set-buffer cur)
961                 (insert-buffer-substring temp))))
962         (mm-with-unibyte-buffer
963           (insert-buffer-substring (mm-handle-buffer handle))
964           (prog1
965               (mm-decode-content-transfer-encoding
966                (mm-handle-encoding handle)
967                (mm-handle-media-type handle))
968             (let ((temp (current-buffer)))
969               (set-buffer cur)
970               (insert-buffer-substring temp))))))))
971
972 (defun mm-file-name-delete-whitespace (file-name)
973   "Remove all whitespace characters from FILE-NAME."
974   (while (string-match "\\s-+" file-name)
975     (setq file-name (replace-match "" t t file-name)))
976   file-name)
977
978 (defun mm-file-name-trim-whitespace (file-name)
979   "Remove leading and trailing whitespace characters from FILE-NAME."
980   (when (string-match "\\`\\s-+" file-name)
981     (setq file-name (substring file-name (match-end 0))))
982   (when (string-match "\\s-+\\'" file-name)
983     (setq file-name (substring file-name 0 (match-beginning 0))))
984   file-name)
985
986 (defun mm-file-name-collapse-whitespace (file-name)
987   "Collapse multiple whitespace characters in FILE-NAME."
988   (while (string-match "\\s-\\s-+" file-name)
989     (setq file-name (replace-match " " t t file-name)))
990   file-name)
991
992 (defun mm-file-name-replace-whitespace (file-name)
993   "Replace whitespace characters in FILE-NAME with underscores.
994 Set `mm-file-name-replace-whitespace' to any other string if you do not
995 like underscores."
996   (let ((s (or mm-file-name-replace-whitespace "_")))
997     (while (string-match "\\s-" file-name)
998       (setq file-name (replace-match s t t file-name))))
999   file-name)
1000
1001 (defun mm-save-part (handle)
1002   "Write HANDLE to a file."
1003   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
1004          (filename (mail-content-type-get
1005                     (mm-handle-disposition handle) 'filename))
1006          file)
1007     (when filename
1008       (setq filename (gnus-map-function mm-file-name-rewrite-functions
1009                                         (file-name-nondirectory filename))))
1010     (setq file
1011           (read-file-name "Save MIME part to: "
1012                           (expand-file-name
1013                            (or filename name "")
1014                            (or mm-default-directory default-directory))))
1015     (setq mm-default-directory (file-name-directory file))
1016     (and (or (not (file-exists-p file))
1017              (yes-or-no-p (format "File %s already exists; overwrite? "
1018                                   file)))
1019          (progn
1020            (mm-save-part-to-file handle file)
1021            file))))
1022
1023 (defun mm-save-part-to-file (handle file)
1024   (mm-with-unibyte-buffer
1025     (mm-insert-part handle)
1026     (let ((coding-system-for-write 'binary)
1027           ;; Don't re-compress .gz & al.  Arguably we should make
1028           ;; `file-name-handler-alist' nil, but that would chop
1029           ;; ange-ftp, which is reasonable to use here.
1030           (inhibit-file-name-operation 'write-region)
1031           (inhibit-file-name-handlers
1032            (cons 'jka-compr-handler inhibit-file-name-handlers)))
1033       (write-region (point-min) (point-max) file))))
1034
1035 (defun mm-pipe-part (handle)
1036   "Pipe HANDLE to a process."
1037   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
1038          (command
1039           (read-string "Shell command on MIME part: " mm-last-shell-command)))
1040     (mm-with-unibyte-buffer
1041       (mm-insert-part handle)
1042       (let ((coding-system-for-write 'binary))
1043         (shell-command-on-region (point-min) (point-max) command nil)))))
1044
1045 (defun mm-interactively-view-part (handle)
1046   "Display HANDLE using METHOD."
1047   (let* ((type (mm-handle-media-type handle))
1048          (methods
1049           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
1050                   (mailcap-mime-info type 'all)))
1051          (method (let ((minibuffer-local-completion-map
1052                         mm-viewer-completion-map))
1053                    (completing-read "Viewer: " methods))))
1054     (when (string= method "")
1055       (error "No method given"))
1056     (if (string-match "^[^% \t]+$" method)
1057         (setq method (concat method " %s")))
1058     (mm-display-external handle method)))
1059
1060 (defun mm-preferred-alternative (handles &optional preferred)
1061   "Say which of HANDLES are preferred."
1062   (let ((prec (if preferred (list preferred)
1063                 (mm-preferred-alternative-precedence handles)))
1064         p h result type handle)
1065     (while (setq p (pop prec))
1066       (setq h handles)
1067       (while h
1068         (setq handle (car h))
1069         (setq type (mm-handle-media-type handle))
1070         (when (and (equal p type)
1071                    (mm-automatic-display-p handle)
1072                    (or (stringp (car handle))
1073                        (not (mm-handle-disposition handle))
1074                        (equal (car (mm-handle-disposition handle))
1075                               "inline")))
1076           (setq result handle
1077                 h nil
1078                 prec nil))
1079         (pop h)))
1080     result))
1081
1082 (defun mm-preferred-alternative-precedence (handles)
1083   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
1084   (let ((seq (nreverse (mapcar #'mm-handle-media-type
1085                                handles))))
1086     (dolist (disc (reverse mm-discouraged-alternatives))
1087       (dolist (elem (copy-sequence seq))
1088         (when (string-match disc elem)
1089           (setq seq (nconc (delete elem seq) (list elem))))))
1090     seq))
1091
1092 (defun mm-get-content-id (id)
1093   "Return the handle(s) referred to by ID."
1094   (cdr (assoc id mm-content-id-alist)))
1095
1096 (defconst mm-image-type-regexps
1097   '(("/\\*.*XPM.\\*/" . xpm)
1098     ("P[1-6]" . pbm)
1099     ("GIF8" . gif)
1100     ("\377\330" . jpeg)
1101     ("\211PNG\r\n" . png)
1102     ("#define" . xbm)
1103     ("\\(MM\0\\*\\)\\|\\(II\\*\0\\)" . tiff)
1104     ("%!PS" . postscript))
1105   "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
1106 When the first bytes of an image file match REGEXP, it is assumed to
1107 be of image type IMAGE-TYPE.")
1108
1109 ;; Steal from image.el. image-type-from-data suffers multi-line matching bug.
1110 (defun mm-image-type-from-buffer ()
1111   "Determine the image type from data in the current buffer.
1112 Value is a symbol specifying the image type or nil if type cannot
1113 be determined."
1114   (let ((types mm-image-type-regexps)
1115         type)
1116     (goto-char (point-min))
1117     (while (and types (null type))
1118       (let ((regexp (car (car types)))
1119             (image-type (cdr (car types))))
1120         (when (looking-at regexp)
1121           (setq type image-type))
1122         (setq types (cdr types))))
1123     type))
1124
1125 (defun mm-get-image (handle)
1126   "Return an image instance based on HANDLE."
1127   (let ((type (mm-handle-media-subtype handle))
1128         spec)
1129     ;; Allow some common translations.
1130     (setq type
1131           (cond
1132            ((equal type "x-pixmap")
1133             "xpm")
1134            ((equal type "x-xbitmap")
1135             "xbm")
1136            ((equal type "x-portable-bitmap")
1137             "pbm")
1138            (t type)))
1139     (or (mm-handle-cache handle)
1140         (mm-with-unibyte-buffer
1141           (mm-insert-part handle)
1142           (prog1
1143               (setq spec
1144                     (ignore-errors
1145                       ;; Avoid testing `make-glyph' since W3 may define
1146                       ;; a bogus version of it.
1147                       (if (fboundp 'create-image)
1148                           (create-image (buffer-string) 
1149                                         (or (mm-image-type-from-buffer)
1150                                             (intern type))
1151                                         'data-p)
1152                         (mm-create-image-xemacs type))))
1153             (mm-handle-set-cache handle spec))))))
1154
1155 (defun mm-create-image-xemacs (type)
1156   (cond
1157    ((equal type "xbm")
1158     ;; xbm images require special handling, since
1159     ;; the only way to create glyphs from these
1160     ;; (without a ton of work) is to write them
1161     ;; out to a file, and then create a file
1162     ;; specifier.
1163     (let ((file (make-temp-name
1164                  (expand-file-name "emm.xbm"
1165                                    mm-tmp-directory))))
1166       (unwind-protect
1167           (progn
1168             (write-region (point-min) (point-max) file)
1169             (make-glyph (list (cons 'x file))))
1170         (ignore-errors
1171           (delete-file file)))))
1172    (t
1173     (make-glyph
1174      (vector 
1175       (or (mm-image-type-from-buffer)
1176           (intern type))
1177       :data (buffer-string))))))
1178   
1179 (defun mm-image-fit-p (handle)
1180   "Say whether the image in HANDLE will fit the current window."
1181   (let ((image (mm-get-image handle)))
1182     (if (fboundp 'glyph-width)
1183         ;; XEmacs' glyphs can actually tell us about their width, so
1184         ;; lets be nice and smart about them.
1185         (or mm-inline-large-images
1186             (and (< (glyph-width image) (window-pixel-width))
1187                  (< (glyph-height image) (window-pixel-height))))
1188       (let* ((size (image-size image))
1189              (w (car size))
1190              (h (cdr size)))
1191         (or mm-inline-large-images
1192             (and (< h (1- (window-height))) ; Don't include mode line.
1193                  (< w (window-width))))))))
1194
1195 (defun mm-valid-image-format-p (format)
1196   "Say whether FORMAT can be displayed natively by Emacs."
1197   (cond
1198    ;; Handle XEmacs
1199    ((fboundp 'valid-image-instantiator-format-p)
1200     (valid-image-instantiator-format-p format))
1201    ;; Handle Emacs 21
1202    ((fboundp 'image-type-available-p)
1203     (and (display-graphic-p)
1204          (image-type-available-p format)))
1205    ;; Nobody else can do images yet.
1206    (t
1207     nil)))
1208
1209 (defun mm-valid-and-fit-image-p (format handle)
1210   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
1211   (and (mm-valid-image-format-p format)
1212        (mm-image-fit-p handle)))
1213
1214 (defun mm-find-part-by-type (handles type &optional notp recursive)
1215   "Search in HANDLES for part with TYPE.
1216 If NOTP, returns first non-matching part.
1217 If RECURSIVE, search recursively."
1218   (let (handle)
1219     (while handles
1220       (if (and recursive (stringp (caar handles)))
1221           (if (setq handle (mm-find-part-by-type (cdar handles) type
1222                                                  notp recursive))
1223               (setq handles nil))
1224         (if (if notp
1225                 (not (equal (mm-handle-media-type (car handles)) type))
1226               (equal (mm-handle-media-type (car handles)) type))
1227             (setq handle (car handles)
1228                   handles nil)))
1229       (setq handles (cdr handles)))
1230     handle))
1231
1232 (defun mm-find-raw-part-by-type (ctl type &optional notp)
1233   (goto-char (point-min))
1234   (let* ((boundary (concat "--" (mm-handle-multipart-ctl-parameter ctl
1235                                                                    'boundary)))
1236          (close-delimiter (concat "^" (regexp-quote boundary) "--[ \t]*$"))
1237          start
1238          (end (save-excursion
1239                 (goto-char (point-max))
1240                 (if (re-search-backward close-delimiter nil t)
1241                     (match-beginning 0)
1242                   (point-max))))
1243          result)
1244     (setq boundary (concat "^" (regexp-quote boundary) "[ \t]*$"))
1245     (while (and (not result)
1246                 (re-search-forward boundary end t))
1247       (goto-char (match-beginning 0))
1248       (when start
1249         (save-excursion
1250           (save-restriction
1251             (narrow-to-region start (1- (point)))
1252             (when (let ((ctl (ignore-errors
1253                                (mail-header-parse-content-type
1254                                 (mail-fetch-field "content-type")))))
1255                     (if notp
1256                         (not (equal (car ctl) type))
1257                       (equal (car ctl) type)))
1258               (setq result (buffer-substring (point-min) (point-max)))))))
1259       (forward-line 1)
1260       (setq start (point)))
1261     (when (and (not result) start)
1262       (save-excursion
1263         (save-restriction
1264           (narrow-to-region start end)
1265           (when (let ((ctl (ignore-errors
1266                              (mail-header-parse-content-type
1267                               (mail-fetch-field "content-type")))))
1268                   (if notp
1269                       (not (equal (car ctl) type))
1270                     (equal (car ctl) type)))
1271             (setq result (buffer-substring (point-min) (point-max)))))))
1272     result))
1273
1274 (defvar mm-security-handle nil)
1275
1276 (defsubst mm-set-handle-multipart-parameter (handle parameter value)
1277   ;; HANDLE could be a CTL.
1278   (if handle
1279       (put-text-property 0 (length (car handle)) parameter value
1280                          (car handle))))
1281
1282 (defun mm-possibly-verify-or-decrypt (parts ctl)
1283   (let ((type (car ctl))
1284         (subtype (cadr (split-string (car ctl) "/")))
1285         (mm-security-handle ctl) ;; (car CTL) is the type.
1286         protocol func functest)
1287     (cond
1288      ((or (equal type "application/x-pkcs7-mime")
1289           (equal type "application/pkcs7-mime"))
1290       (with-temp-buffer
1291         (when (and (cond
1292                     ((eq mm-decrypt-option 'never) nil)
1293                     ((eq mm-decrypt-option 'always) t)
1294                     ((eq mm-decrypt-option 'known) t)
1295                     (t (y-or-n-p
1296                         (format "Decrypt (S/MIME) part? "))))
1297                    (mm-view-pkcs7 parts))
1298           (setq parts (mm-dissect-buffer t)))))
1299      ((equal subtype "signed")
1300       (unless (and (setq protocol
1301                          (mm-handle-multipart-ctl-parameter ctl 'protocol))
1302                    (not (equal protocol "multipart/mixed")))
1303         ;; The message is broken or draft-ietf-openpgp-multsig-01.
1304         (let ((protocols mm-verify-function-alist))
1305           (while protocols
1306             (if (and (or (not (setq functest (nth 3 (car protocols))))
1307                          (funcall functest parts ctl))
1308                      (mm-find-part-by-type parts (caar protocols) nil t))
1309                 (setq protocol (caar protocols)
1310                       protocols nil)
1311               (setq protocols (cdr protocols))))))
1312       (setq func (nth 1 (assoc protocol mm-verify-function-alist)))
1313       (if (cond
1314            ((eq mm-verify-option 'never) nil)
1315            ((eq mm-verify-option 'always) t)
1316            ((eq mm-verify-option 'known)
1317             (and func
1318                  (or (not (setq functest
1319                                 (nth 3 (assoc protocol
1320                                               mm-verify-function-alist))))
1321                      (funcall functest parts ctl))))
1322            (t (y-or-n-p
1323                (format "Verify signed (%s) part? "
1324                        (or (nth 2 (assoc protocol mm-verify-function-alist))
1325                            (format "protocol=%s" protocol))))))
1326           (save-excursion
1327             (if func
1328                 (funcall func parts ctl)
1329               (mm-set-handle-multipart-parameter
1330                mm-security-handle 'gnus-details
1331                (format "Unknown sign protocol (%s)" protocol))))))
1332      ((equal subtype "encrypted")
1333       (unless (setq protocol
1334                     (mm-handle-multipart-ctl-parameter ctl 'protocol))
1335         ;; The message is broken.
1336         (let ((parts parts))
1337           (while parts
1338             (if (assoc (mm-handle-media-type (car parts))
1339                        mm-decrypt-function-alist)
1340                 (setq protocol (mm-handle-media-type (car parts))
1341                       parts nil)
1342               (setq parts (cdr parts))))))
1343       (setq func (nth 1 (assoc protocol mm-decrypt-function-alist)))
1344       (if (cond
1345            ((eq mm-decrypt-option 'never) nil)
1346            ((eq mm-decrypt-option 'always) t)
1347            ((eq mm-decrypt-option 'known)
1348             (and func
1349                  (or (not (setq functest
1350                                 (nth 3 (assoc protocol
1351                                               mm-decrypt-function-alist))))
1352                      (funcall functest parts ctl))))
1353            (t (y-or-n-p
1354                (format "Decrypt (%s) part? "
1355                        (or (nth 2 (assoc protocol mm-decrypt-function-alist))
1356                            (format "protocol=%s" protocol))))))
1357           (save-excursion
1358             (if func
1359                 (setq parts (funcall func parts ctl))
1360               (mm-set-handle-multipart-parameter
1361                mm-security-handle 'gnus-details
1362                (format "Unknown encrypt protocol (%s)" protocol))))))
1363      (t nil))
1364     parts))
1365
1366 (defun mm-multiple-handles (handles)
1367   (and (listp (car handles))
1368        (> (length handles) 1)))
1369
1370 (defun mm-merge-handles (handles1 handles2)
1371   (append
1372    (if (listp (car handles1))
1373        handles1
1374      (list handles1))
1375    (if (listp (car handles2))
1376        handles2
1377      (list handles2))))
1378
1379 (defun mm-readable-p (handle)
1380   "Say whether the content of HANDLE is readable."
1381   (and (< (with-current-buffer (mm-handle-buffer handle)
1382             (buffer-size)) 10000)
1383        (mm-with-unibyte-buffer
1384          (mm-insert-part handle)
1385          (and (eq (mm-body-7-or-8) '7bit)
1386               (not (mm-long-lines-p 76))))))
1387
1388 (provide 'mm-decode)
1389
1390 ;;; mm-decode.el ends here