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