d80fde09a99d23c9fdcbfd6cf610576e6de4291e
[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       (forward-line 2)
571       (setq start (point)))
572     (when (and start (< start end))
573       (save-excursion
574         (save-restriction
575           (narrow-to-region start end)
576           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
577     (mm-possibly-verify-or-decrypt (nreverse parts) ctl)))
578
579 (defun mm-copy-to-buffer ()
580   "Copy the contents of the current buffer to a fresh buffer."
581   (save-excursion
582     (let ((obuf (current-buffer))
583           beg)
584       (goto-char (point-min))
585       (search-forward-regexp "^\n" nil t)
586       (setq beg (point))
587       (set-buffer (generate-new-buffer " *mm*"))
588       (insert-buffer-substring obuf beg)
589       (current-buffer))))
590
591 (defun mm-display-parts (handle &optional no-default)
592   (if (stringp (car handle))
593       (mapcar 'mm-display-parts (cdr handle))
594     (if (bufferp (car handle))
595         (save-restriction
596           (narrow-to-region (point) (point))
597           (mm-display-part handle)
598           (goto-char (point-max)))
599       (mapcar 'mm-display-parts handle))))
600
601 (defun mm-display-part (handle &optional no-default)
602   "Display the MIME part represented by HANDLE.
603 Returns nil if the part is removed; inline if displayed inline;
604 external if displayed external."
605   (save-excursion
606     (mailcap-parse-mailcaps)
607     (if (mm-handle-displayed-p handle)
608         (mm-remove-part handle)
609       (let* ((type (mm-handle-media-type handle))
610              (method (mailcap-mime-info type)))
611         (if (and (mm-inlinable-p handle)
612                  (mm-inlined-p handle))
613             (progn
614               (forward-line 1)
615               (mm-display-inline handle)
616               'inline)
617           (when (or method
618                     (not no-default))
619             (if (and (not method)
620                      (equal "text" (car (split-string type))))
621                 (progn
622                   (forward-line 1)
623                   (mm-insert-inline handle (mm-get-part handle))
624                   'inline)
625               (mm-display-external
626                handle (or method 'mailcap-save-binary-file)))))))))
627
628 (defun mm-display-external (handle method)
629   "Display HANDLE using METHOD."
630   (let ((outbuf (current-buffer)))
631     (mm-with-unibyte-buffer
632       (if (functionp method)
633           (let ((cur (current-buffer)))
634             (if (eq method 'mailcap-save-binary-file)
635                 (progn
636                   (set-buffer (generate-new-buffer " *mm*"))
637                   (setq method nil))
638               (mm-insert-part handle)
639               (let ((win (get-buffer-window cur t)))
640                 (when win
641                   (select-window win)))
642               (switch-to-buffer (generate-new-buffer " *mm*")))
643             (buffer-disable-undo)
644             (mm-set-buffer-file-coding-system mm-binary-coding-system)
645             (insert-buffer-substring cur)
646             (goto-char (point-min))
647             (message "Viewing with %s" method)
648             (let ((mm (current-buffer))
649                   (non-viewer (assq 'non-viewer
650                                     (mailcap-mime-info
651                                      (mm-handle-media-type handle) t))))
652               (unwind-protect
653                   (if method
654                       (funcall method)
655                     (mm-save-part handle))
656                 (when (and (not non-viewer)
657                            method)
658                   (mm-handle-set-undisplayer handle mm)))))
659         ;; The function is a string to be executed.
660         (mm-insert-part handle)
661         (let* ((dir (make-temp-name
662                      (expand-file-name "emm." mm-tmp-directory)))
663                (filename (or 
664                           (mail-content-type-get
665                            (mm-handle-disposition handle) 'filename)
666                           (mail-content-type-get
667                            (mm-handle-type handle) 'name)))
668                (mime-info (mailcap-mime-info
669                            (mm-handle-media-type handle) t))
670                (needsterm (or (assoc "needsterm" mime-info)
671                               (assoc "needsterminal" mime-info)))
672                (copiousoutput (assoc "copiousoutput" mime-info))
673                file buffer)
674           ;; We create a private sub-directory where we store our files.
675           (make-directory dir)
676           (set-file-modes dir 448)
677           (if filename
678               (setq file (expand-file-name (file-name-nondirectory filename)
679                                            dir))
680             (setq file (make-temp-name (expand-file-name "mm." dir))))
681           (let ((coding-system-for-write mm-binary-coding-system))
682             (write-region (point-min) (point-max) file nil 'nomesg))
683           (message "Viewing with %s" method)
684           (cond
685            (needsterm
686             (unwind-protect
687                 (if window-system
688                     (start-process "*display*" nil
689                                    mm-external-terminal-program
690                                    "-e" shell-file-name
691                                    shell-command-switch
692                                    (mm-mailcap-command
693                                     method file (mm-handle-type handle)))
694                   (require 'term)
695                   (require 'gnus-win)
696                   (set-buffer
697                    (setq buffer
698                          (make-term "display"
699                                     shell-file-name
700                                     nil
701                                     shell-command-switch
702                                     (mm-mailcap-command
703                                      method file
704                                      (mm-handle-type handle)))))
705                   (term-mode)
706                   (term-char-mode)
707                   (set-process-sentinel
708                    (get-buffer-process buffer)
709                    `(lambda (process state)
710                       (if (eq 'exit (process-status process))
711                           (gnus-configure-windows
712                            ',gnus-current-window-configuration))))
713                   (gnus-configure-windows 'display-term))
714               (mm-handle-set-external-undisplayer handle (cons file buffer)))
715             (message "Displaying %s..." (format method file))
716             'external)
717            (copiousoutput
718             (with-current-buffer outbuf
719               (forward-line 1)
720               (mm-insert-inline
721                handle
722                (unwind-protect
723                    (progn
724                      (call-process shell-file-name nil
725                                    (setq buffer
726                                          (generate-new-buffer " *mm*"))
727                                    nil
728                                    shell-command-switch
729                                    (mm-mailcap-command
730                                     method file (mm-handle-type handle)))
731                      (if (buffer-live-p buffer)
732                          (save-excursion
733                            (set-buffer buffer)
734                            (buffer-string))))
735                  (progn
736                    (ignore-errors (delete-file file))
737                    (ignore-errors (delete-directory
738                                    (file-name-directory file)))
739                    (ignore-errors (kill-buffer buffer))))))
740             'inline)
741            (t
742             (unwind-protect
743                 (start-process "*display*"
744                                (setq buffer
745                                      (generate-new-buffer " *mm*"))
746                                shell-file-name
747                                shell-command-switch
748                                (mm-mailcap-command
749                                 method file (mm-handle-type handle)))
750               (mm-handle-set-external-undisplayer
751                handle (cons file buffer)))
752             (message "Displaying %s..." (format method file))
753             'external)))))))
754
755 (defun mm-mailcap-command (method file type-list)
756   (let ((ctl (cdr type-list))
757         (beg 0)
758         (uses-stdin t)
759         out sub total)
760     (while (string-match "%{\\([^}]+\\)}\\|%s\\|%t\\|%%" method beg)
761       (push (substring method beg (match-beginning 0)) out)
762       (setq beg (match-end 0)
763             total (match-string 0 method)
764             sub (match-string 1 method))
765       (cond
766        ((string= total "%%")
767         (push "%" out))
768        ((string= total "%s")
769         (setq uses-stdin nil)
770         (push (mm-quote-arg
771                (gnus-map-function mm-path-name-rewrite-functions file)) out))
772        ((string= total "%t")
773         (push (mm-quote-arg (car type-list)) out))
774        (t
775         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
776     (push (substring method beg (length method)) out)
777     (when uses-stdin
778       (push "<" out)
779       (push (mm-quote-arg
780              (gnus-map-function mm-path-name-rewrite-functions file))
781             out))
782     (mapconcat 'identity (nreverse out) "")))
783
784 (defun mm-remove-parts (handles)
785   "Remove the displayed MIME parts represented by HANDLES."
786   (if (and (listp handles)
787            (bufferp (car handles)))
788       (mm-remove-part handles)
789     (let (handle)
790       (while (setq handle (pop handles))
791         (cond
792          ((stringp handle)
793           (when (buffer-live-p (get-text-property 0 'buffer handle))
794             (kill-buffer (get-text-property 0 'buffer handle))))
795          ((and (listp handle)
796                (stringp (car handle)))
797           (mm-remove-parts (cdr handle)))
798          (t
799           (mm-remove-part handle)))))))
800
801 (defun mm-destroy-parts (handles)
802   "Remove the displayed MIME parts represented by HANDLES."
803   (if (and (listp handles)
804            (bufferp (car handles)))
805       (mm-destroy-part handles)
806     (let (handle)
807       (while (setq handle (pop handles))
808         (cond
809          ((stringp handle)
810           (when (buffer-live-p (get-text-property 0 'buffer handle))
811             (kill-buffer (get-text-property 0 'buffer handle))))
812          ((and (listp handle)
813                (stringp (car handle)))
814           (mm-destroy-parts handle))
815          (t
816           (mm-destroy-part handle)))))))
817
818 (defun mm-remove-part (handle)
819   "Remove the displayed MIME part represented by HANDLE."
820   (when (listp handle)
821     (let ((object (mm-handle-undisplayer handle)))
822       (ignore-errors
823         (cond
824          ;; Internally displayed part.
825          ((mm-annotationp object)
826           (delete-annotation object))
827          ((or (functionp object)
828               (and (listp object)
829                    (eq (car object) 'lambda)))
830           (funcall object))
831          ;; Externally displayed part.
832          ((consp object)
833           (ignore-errors (delete-file (car object)))
834           (ignore-errors (delete-directory (file-name-directory (car object))))
835           (ignore-errors (and (cdr object) (kill-buffer (cdr object)))))
836          ((bufferp object)
837           (when (buffer-live-p object)
838             (kill-buffer object)))))
839       (mm-handle-set-undisplayer handle nil))))
840
841 (defun mm-display-inline (handle)
842   (let* ((type (mm-handle-media-type handle))
843          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
844     (funcall function handle)
845     (goto-char (point-min))))
846
847 (defun mm-assoc-string-match (alist type)
848   (dolist (elem alist)
849     (when (string-match (car elem) type)
850       (return elem))))
851
852 (defun mm-automatic-display-p (handle)
853   "Say whether the user wants HANDLE to be displayed automatically."
854   (let ((methods mm-automatic-display)
855         (type (mm-handle-media-type handle))
856         method result)
857     (while (setq method (pop methods))
858       (when (and (not (mm-inline-override-p handle))
859                  (string-match method type))
860         (setq result t
861               methods nil)))
862     result))
863
864 (defun mm-inlinable-p (handle)
865   "Say whether HANDLE can be displayed inline."
866   (let ((alist mm-inline-media-tests)
867         (type (mm-handle-media-type handle))
868         test)
869     (while alist
870       (when (string-match (caar alist) type)
871         (setq test (caddar alist)
872               alist nil)
873         (setq test (funcall test handle)))
874       (pop alist))
875     test))
876
877 (defun mm-inlined-p (handle)
878   "Say whether the user wants HANDLE to be displayed inline."
879   (let ((methods mm-inlined-types)
880         (type (mm-handle-media-type handle))
881         method result)
882     (while (setq method (pop methods))
883       (when (and (not (mm-inline-override-p handle))
884                  (string-match method type))
885         (setq result t
886               methods nil)))
887     result))
888
889 (defun mm-attachment-override-p (handle)
890   "Say whether HANDLE should have attachment behavior overridden."
891   (let ((types mm-attachment-override-types)
892         (type (mm-handle-media-type handle))
893         ty)
894     (catch 'found
895       (while (setq ty (pop types))
896         (when (and (string-match ty type)
897                    (mm-inlinable-p handle))
898           (throw 'found t))))))
899
900 (defun mm-inline-override-p (handle)
901   "Say whether HANDLE should have inline behavior overridden."
902   (let ((types mm-inline-override-types)
903         (type (mm-handle-media-type handle))
904         ty)
905     (catch 'found
906       (while (setq ty (pop types))
907         (when (string-match ty type)
908           (throw 'found t))))))
909
910 (defun mm-automatic-external-display-p (type)
911   "Return the user-defined method for TYPE."
912   (let ((methods mm-automatic-external-display)
913         method result)
914     (while (setq method (pop methods))
915       (when (string-match method type)
916         (setq result t
917               methods nil)))
918     result))
919
920 (defun mm-destroy-part (handle)
921   "Destroy the data structures connected to HANDLE."
922   (when (listp handle)
923     (mm-remove-part handle)
924     (when (buffer-live-p (mm-handle-buffer handle))
925       (kill-buffer (mm-handle-buffer handle)))))
926
927 (defun mm-handle-displayed-p (handle)
928   "Say whether HANDLE is displayed or not."
929   (mm-handle-undisplayer handle))
930
931 ;;;
932 ;;; Functions for outputting parts
933 ;;;
934
935 (defun mm-get-part (handle)
936   "Return the contents of HANDLE as a string."
937   (mm-with-unibyte-buffer
938     (insert (with-current-buffer (mm-handle-buffer handle)
939               (mm-with-unibyte-current-buffer-mule4
940                 (buffer-string))))
941     (mm-decode-content-transfer-encoding
942      (mm-handle-encoding handle)
943      (mm-handle-media-type handle))
944     (buffer-string)))
945
946 (defun mm-insert-part (handle)
947   "Insert the contents of HANDLE in the current buffer."
948   (let ((cur (current-buffer)))
949     (save-excursion
950       (if (member (mm-handle-media-supertype handle) '("text" "message"))
951           (with-temp-buffer
952             (insert-buffer-substring (mm-handle-buffer handle))
953             (prog1
954                 (mm-decode-content-transfer-encoding
955                  (mm-handle-encoding handle)
956                  (mm-handle-media-type handle))
957               (let ((temp (current-buffer)))
958                 (set-buffer cur)
959                 (insert-buffer-substring temp))))
960         (mm-with-unibyte-buffer
961           (insert-buffer-substring (mm-handle-buffer handle))
962           (prog1
963               (mm-decode-content-transfer-encoding
964                (mm-handle-encoding handle)
965                (mm-handle-media-type handle))
966             (let ((temp (current-buffer)))
967               (set-buffer cur)
968               (insert-buffer-substring temp))))))))
969
970 (defun mm-file-name-delete-whitespace (file-name)
971   "Remove all whitespace characters from FILE-NAME."
972   (while (string-match "\\s-+" file-name)
973     (setq file-name (replace-match "" t t file-name)))
974   file-name)
975
976 (defun mm-file-name-trim-whitespace (file-name)
977   "Remove leading and trailing whitespace characters from FILE-NAME."
978   (when (string-match "\\`\\s-+" file-name)
979     (setq file-name (substring file-name (match-end 0))))
980   (when (string-match "\\s-+\\'" file-name)
981     (setq file-name (substring file-name 0 (match-beginning 0))))
982   file-name)
983
984 (defun mm-file-name-collapse-whitespace (file-name)
985   "Collapse multiple whitespace characters in FILE-NAME."
986   (while (string-match "\\s-\\s-+" file-name)
987     (setq file-name (replace-match " " t t file-name)))
988   file-name)
989
990 (defun mm-file-name-replace-whitespace (file-name)
991   "Replace whitespace characters in FILE-NAME with underscores.
992 Set `mm-file-name-replace-whitespace' to any other string if you do not
993 like underscores."
994   (let ((s (or mm-file-name-replace-whitespace "_")))
995     (while (string-match "\\s-" file-name)
996       (setq file-name (replace-match s t t file-name))))
997   file-name)
998
999 (defun mm-save-part (handle)
1000   "Write HANDLE to a file."
1001   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
1002          (filename (mail-content-type-get
1003                     (mm-handle-disposition handle) 'filename))
1004          file)
1005     (when filename
1006       (setq filename (gnus-map-function mm-file-name-rewrite-functions
1007                                         (file-name-nondirectory filename))))
1008     (setq file
1009           (read-file-name "Save MIME part to: "
1010                           (expand-file-name
1011                            (or filename name "")
1012                            (or mm-default-directory default-directory))))
1013     (setq mm-default-directory (file-name-directory file))
1014     (and (or (not (file-exists-p file))
1015              (yes-or-no-p (format "File %s already exists; overwrite? "
1016                                   file)))
1017          (progn
1018            (mm-save-part-to-file handle file)
1019            file))))
1020
1021 (defun mm-save-part-to-file (handle file)
1022   (mm-with-unibyte-buffer
1023     (mm-insert-part handle)
1024     (let ((coding-system-for-write 'binary)
1025           ;; Don't re-compress .gz & al.  Arguably we should make
1026           ;; `file-name-handler-alist' nil, but that would chop
1027           ;; ange-ftp, which is reasonable to use here.
1028           (inhibit-file-name-operation 'write-region)
1029           (inhibit-file-name-handlers
1030            (cons 'jka-compr-handler inhibit-file-name-handlers)))
1031       (write-region (point-min) (point-max) file))))
1032
1033 (defun mm-pipe-part (handle)
1034   "Pipe HANDLE to a process."
1035   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
1036          (command
1037           (read-string "Shell command on MIME part: " mm-last-shell-command)))
1038     (mm-with-unibyte-buffer
1039       (mm-insert-part handle)
1040       (let ((coding-system-for-write 'binary))
1041         (shell-command-on-region (point-min) (point-max) command nil)))))
1042
1043 (defun mm-interactively-view-part (handle)
1044   "Display HANDLE using METHOD."
1045   (let* ((type (mm-handle-media-type handle))
1046          (methods
1047           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
1048                   (mailcap-mime-info type 'all)))
1049          (method (let ((minibuffer-local-completion-map
1050                         mm-viewer-completion-map))
1051                    (completing-read "Viewer: " methods))))
1052     (when (string= method "")
1053       (error "No method given"))
1054     (if (string-match "^[^% \t]+$" method)
1055         (setq method (concat method " %s")))
1056     (mm-display-external handle method)))
1057
1058 (defun mm-preferred-alternative (handles &optional preferred)
1059   "Say which of HANDLES are preferred."
1060   (let ((prec (if preferred (list preferred)
1061                 (mm-preferred-alternative-precedence handles)))
1062         p h result type handle)
1063     (while (setq p (pop prec))
1064       (setq h handles)
1065       (while h
1066         (setq handle (car h))
1067         (setq type (mm-handle-media-type handle))
1068         (when (and (equal p type)
1069                    (mm-automatic-display-p handle)
1070                    (or (stringp (car handle))
1071                        (not (mm-handle-disposition handle))
1072                        (equal (car (mm-handle-disposition handle))
1073                               "inline")))
1074           (setq result handle
1075                 h nil
1076                 prec nil))
1077         (pop h)))
1078     result))
1079
1080 (defun mm-preferred-alternative-precedence (handles)
1081   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
1082   (let ((seq (nreverse (mapcar #'mm-handle-media-type
1083                                handles))))
1084     (dolist (disc (reverse mm-discouraged-alternatives))
1085       (dolist (elem (copy-sequence seq))
1086         (when (string-match disc elem)
1087           (setq seq (nconc (delete elem seq) (list elem))))))
1088     seq))
1089
1090 (defun mm-get-content-id (id)
1091   "Return the handle(s) referred to by ID."
1092   (cdr (assoc id mm-content-id-alist)))
1093
1094 (defconst mm-image-type-regexps
1095   '(("/\\*.*XPM.\\*/" . xpm)
1096     ("P[1-6]" . pbm)
1097     ("GIF8" . gif)
1098     ("\377\330" . jpeg)
1099     ("\211PNG\r\n" . png)
1100     ("#define" . xbm)
1101     ("\\(MM\0\\*\\)\\|\\(II\\*\0\\)" . tiff)
1102     ("%!PS" . postscript))
1103   "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
1104 When the first bytes of an image file match REGEXP, it is assumed to
1105 be of image type IMAGE-TYPE.")
1106
1107 ;; Steal from image.el. image-type-from-data suffers multi-line matching bug.
1108 (defun mm-image-type-from-buffer ()
1109   "Determine the image type from data in the current buffer.
1110 Value is a symbol specifying the image type or nil if type cannot
1111 be determined."
1112   (let ((types mm-image-type-regexps)
1113         type)
1114     (goto-char (point-min))
1115     (while (and types (null type))
1116       (let ((regexp (car (car types)))
1117             (image-type (cdr (car types))))
1118         (when (looking-at regexp)
1119           (setq type image-type))
1120         (setq types (cdr types))))
1121     type))
1122
1123 (defun mm-get-image (handle)
1124   "Return an image instance based on HANDLE."
1125   (let ((type (mm-handle-media-subtype handle))
1126         spec)
1127     ;; Allow some common translations.
1128     (setq type
1129           (cond
1130            ((equal type "x-pixmap")
1131             "xpm")
1132            ((equal type "x-xbitmap")
1133             "xbm")
1134            ((equal type "x-portable-bitmap")
1135             "pbm")
1136            (t type)))
1137     (or (mm-handle-cache handle)
1138         (mm-with-unibyte-buffer
1139           (mm-insert-part handle)
1140           (prog1
1141               (setq spec
1142                     (ignore-errors
1143                       ;; Avoid testing `make-glyph' since W3 may define
1144                       ;; a bogus version of it.
1145                       (if (fboundp 'create-image)
1146                           (create-image (buffer-string) 
1147                                         (or (mm-image-type-from-buffer)
1148                                             (intern type))
1149                                         'data-p)
1150                         (mm-create-image-xemacs type))))
1151             (mm-handle-set-cache handle spec))))))
1152
1153 (defun mm-create-image-xemacs (type)
1154   (cond
1155    ((equal type "xbm")
1156     ;; xbm images require special handling, since
1157     ;; the only way to create glyphs from these
1158     ;; (without a ton of work) is to write them
1159     ;; out to a file, and then create a file
1160     ;; specifier.
1161     (let ((file (make-temp-name
1162                  (expand-file-name "emm.xbm"
1163                                    mm-tmp-directory))))
1164       (unwind-protect
1165           (progn
1166             (write-region (point-min) (point-max) file)
1167             (make-glyph (list (cons 'x file))))
1168         (ignore-errors
1169           (delete-file file)))))
1170    (t
1171     (make-glyph
1172      (vector 
1173       (or (mm-image-type-from-buffer)
1174           (intern type))
1175       :data (buffer-string))))))
1176   
1177 (defun mm-image-fit-p (handle)
1178   "Say whether the image in HANDLE will fit the current window."
1179   (let ((image (mm-get-image handle)))
1180     (if (fboundp 'glyph-width)
1181         ;; XEmacs' glyphs can actually tell us about their width, so
1182         ;; lets be nice and smart about them.
1183         (or mm-inline-large-images
1184             (and (< (glyph-width image) (window-pixel-width))
1185                  (< (glyph-height image) (window-pixel-height))))
1186       (let* ((size (image-size image))
1187              (w (car size))
1188              (h (cdr size)))
1189         (or mm-inline-large-images
1190             (and (< h (1- (window-height))) ; Don't include mode line.
1191                  (< w (window-width))))))))
1192
1193 (defun mm-valid-image-format-p (format)
1194   "Say whether FORMAT can be displayed natively by Emacs."
1195   (cond
1196    ;; Handle XEmacs
1197    ((fboundp 'valid-image-instantiator-format-p)
1198     (valid-image-instantiator-format-p format))
1199    ;; Handle Emacs 21
1200    ((fboundp 'image-type-available-p)
1201     (and (display-graphic-p)
1202          (image-type-available-p format)))
1203    ;; Nobody else can do images yet.
1204    (t
1205     nil)))
1206
1207 (defun mm-valid-and-fit-image-p (format handle)
1208   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
1209   (and (mm-valid-image-format-p format)
1210        (mm-image-fit-p handle)))
1211
1212 (defun mm-find-part-by-type (handles type &optional notp recursive)
1213   "Search in HANDLES for part with TYPE.
1214 If NOTP, returns first non-matching part.
1215 If RECURSIVE, search recursively."
1216   (let (handle)
1217     (while handles
1218       (if (and recursive (stringp (caar handles)))
1219           (if (setq handle (mm-find-part-by-type (cdar handles) type
1220                                                  notp recursive))
1221               (setq handles nil))
1222         (if (if notp
1223                 (not (equal (mm-handle-media-type (car handles)) type))
1224               (equal (mm-handle-media-type (car handles)) type))
1225             (setq handle (car handles)
1226                   handles nil)))
1227       (setq handles (cdr handles)))
1228     handle))
1229
1230 (defun mm-find-raw-part-by-type (ctl type &optional notp)
1231   (goto-char (point-min))
1232   (let* ((boundary (concat "--" (mm-handle-multipart-ctl-parameter ctl
1233                                                                    'boundary)))
1234          (close-delimiter (concat "^" (regexp-quote boundary) "--[ \t]*$"))
1235          start
1236          (end (save-excursion
1237                 (goto-char (point-max))
1238                 (if (re-search-backward close-delimiter nil t)
1239                     (match-beginning 0)
1240                   (point-max))))
1241          result)
1242     (setq boundary (concat "^" (regexp-quote boundary) "[ \t]*$"))
1243     (while (and (not result)
1244                 (re-search-forward boundary end t))
1245       (goto-char (match-beginning 0))
1246       (when start
1247         (save-excursion
1248           (save-restriction
1249             (narrow-to-region start (1- (point)))
1250             (when (let ((ctl (ignore-errors
1251                                (mail-header-parse-content-type
1252                                 (mail-fetch-field "content-type")))))
1253                     (if notp
1254                         (not (equal (car ctl) type))
1255                       (equal (car ctl) type)))
1256               (setq result (buffer-substring (point-min) (point-max)))))))
1257       (forward-line 1)
1258       (setq start (point)))
1259     (when (and (not result) start)
1260       (save-excursion
1261         (save-restriction
1262           (narrow-to-region start end)
1263           (when (let ((ctl (ignore-errors
1264                              (mail-header-parse-content-type
1265                               (mail-fetch-field "content-type")))))
1266                   (if notp
1267                       (not (equal (car ctl) type))
1268                     (equal (car ctl) type)))
1269             (setq result (buffer-substring (point-min) (point-max)))))))
1270     result))
1271
1272 (defvar mm-security-handle nil)
1273
1274 (defsubst mm-set-handle-multipart-parameter (handle parameter value)
1275   ;; HANDLE could be a CTL.
1276   (if handle
1277       (put-text-property 0 (length (car handle)) parameter value
1278                          (car handle))))
1279
1280 (defun mm-possibly-verify-or-decrypt (parts ctl)
1281   (let ((type (car ctl))
1282         (subtype (cadr (split-string (car ctl) "/")))
1283         (mm-security-handle ctl) ;; (car CTL) is the type.
1284         protocol func functest)
1285     (cond
1286      ((or (equal type "application/x-pkcs7-mime")
1287           (equal type "application/pkcs7-mime"))
1288       (with-temp-buffer
1289         (when (and (cond
1290                     ((eq mm-decrypt-option 'never) nil)
1291                     ((eq mm-decrypt-option 'always) t)
1292                     ((eq mm-decrypt-option 'known) t)
1293                     (t (y-or-n-p
1294                         (format "Decrypt (S/MIME) part? "))))
1295                    (mm-view-pkcs7 parts))
1296           (setq parts (mm-dissect-buffer t)))))
1297      ((equal subtype "signed")
1298       (unless (and (setq protocol
1299                          (mm-handle-multipart-ctl-parameter ctl 'protocol))
1300                    (not (equal protocol "multipart/mixed")))
1301         ;; The message is broken or draft-ietf-openpgp-multsig-01.
1302         (let ((protocols mm-verify-function-alist))
1303           (while protocols
1304             (if (and (or (not (setq functest (nth 3 (car protocols))))
1305                          (funcall functest parts ctl))
1306                      (mm-find-part-by-type parts (caar protocols) nil t))
1307                 (setq protocol (caar protocols)
1308                       protocols nil)
1309               (setq protocols (cdr protocols))))))
1310       (setq func (nth 1 (assoc protocol mm-verify-function-alist)))
1311       (if (cond
1312            ((eq mm-verify-option 'never) nil)
1313            ((eq mm-verify-option 'always) t)
1314            ((eq mm-verify-option 'known)
1315             (and func
1316                  (or (not (setq functest
1317                                 (nth 3 (assoc protocol
1318                                               mm-verify-function-alist))))
1319                      (funcall functest parts ctl))))
1320            (t (y-or-n-p
1321                (format "Verify signed (%s) part? "
1322                        (or (nth 2 (assoc protocol mm-verify-function-alist))
1323                            (format "protocol=%s" protocol))))))
1324           (save-excursion
1325             (if func
1326                 (funcall func parts ctl)
1327               (mm-set-handle-multipart-parameter
1328                mm-security-handle 'gnus-details
1329                (format "Unknown sign protocol (%s)" protocol))))))
1330      ((equal subtype "encrypted")
1331       (unless (setq protocol
1332                     (mm-handle-multipart-ctl-parameter ctl 'protocol))
1333         ;; The message is broken.
1334         (let ((parts parts))
1335           (while parts
1336             (if (assoc (mm-handle-media-type (car parts))
1337                        mm-decrypt-function-alist)
1338                 (setq protocol (mm-handle-media-type (car parts))
1339                       parts nil)
1340               (setq parts (cdr parts))))))
1341       (setq func (nth 1 (assoc protocol mm-decrypt-function-alist)))
1342       (if (cond
1343            ((eq mm-decrypt-option 'never) nil)
1344            ((eq mm-decrypt-option 'always) t)
1345            ((eq mm-decrypt-option 'known)
1346             (and func
1347                  (or (not (setq functest
1348                                 (nth 3 (assoc protocol
1349                                               mm-decrypt-function-alist))))
1350                      (funcall functest parts ctl))))
1351            (t (y-or-n-p
1352                (format "Decrypt (%s) part? "
1353                        (or (nth 2 (assoc protocol mm-decrypt-function-alist))
1354                            (format "protocol=%s" protocol))))))
1355           (save-excursion
1356             (if func
1357                 (setq parts (funcall func parts ctl))
1358               (mm-set-handle-multipart-parameter
1359                mm-security-handle 'gnus-details
1360                (format "Unknown encrypt protocol (%s)" protocol))))))
1361      (t nil))
1362     parts))
1363
1364 (defun mm-multiple-handles (handles)
1365   (and (listp (car handles))
1366        (> (length handles) 1)))
1367
1368 (defun mm-merge-handles (handles1 handles2)
1369   (append
1370    (if (listp (car handles1))
1371        handles1
1372      (list handles1))
1373    (if (listp (car handles2))
1374        handles2
1375      (list handles2))))
1376
1377 (defun mm-readable-p (handle)
1378   "Say whether the content of HANDLE is readable."
1379   (and (< (with-current-buffer (mm-handle-buffer handle)
1380             (buffer-size)) 10000)
1381        (mm-with-unibyte-buffer
1382          (mm-insert-part handle)
1383          (and (eq (mm-body-7-or-8) '7bit)
1384               (not (mm-long-lines-p 76))))))
1385
1386 (provide 'mm-decode)
1387
1388 ;;; mm-decode.el ends here