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