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