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