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