2000-11-30 Simon Josefsson <sj@extundo.com>
[gnus] / lisp / mm-decode.el
1 ;;; mm-decode.el --- Functions for decoding MIME things
2 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'mail-parse)
28 (require 'mailcap)
29 (require 'mm-bodies)
30 (eval-when-compile (require 'cl))
31
32 (eval-and-compile
33   (autoload 'mm-inline-partial "mm-partial")
34   (autoload 'mm-inline-external-body "mm-extern"))
35
36 (defgroup mime-display ()
37   "Display of MIME in mail and news articles."
38   :link '(custom-manual "(emacs-mime)Customization")
39   :group 'mail
40   :group 'news
41   :group 'multimedia)
42
43 (defgroup mime-security ()
44   "MIME security in mail and news articles."
45   :link '(custom-manual "(emacs-mime)Customization")
46   :group 'mail
47   :group 'news
48   :group 'multimedia)
49
50 ;;; Convenience macros.
51
52 (defmacro mm-handle-buffer (handle)
53   `(nth 0 ,handle))
54 (defmacro mm-handle-type (handle)
55   `(nth 1 ,handle))
56 (defsubst mm-handle-media-type (handle)
57   (if (stringp (car handle))
58       (car handle)
59     (car (mm-handle-type handle))))
60 (defsubst mm-handle-media-supertype (handle)
61   (car (split-string (mm-handle-media-type handle) "/")))
62 (defsubst mm-handle-media-subtype (handle)
63   (cadr (split-string (mm-handle-media-type handle) "/")))
64 (defmacro mm-handle-encoding (handle)
65   `(nth 2 ,handle))
66 (defmacro mm-handle-undisplayer (handle)
67   `(nth 3 ,handle))
68 (defmacro mm-handle-set-undisplayer (handle function)
69   `(setcar (nthcdr 3 ,handle) ,function))
70 (defmacro mm-handle-disposition (handle)
71   `(nth 4 ,handle))
72 (defmacro mm-handle-description (handle)
73   `(nth 5 ,handle))
74 (defmacro mm-handle-cache (handle)
75   `(nth 6 ,handle))
76 (defmacro mm-handle-set-cache (handle contents)
77   `(setcar (nthcdr 6 ,handle) ,contents))
78 (defmacro mm-handle-id (handle)
79   `(nth 7 ,handle))
80 (defmacro mm-handle-multipart-original-buffer (handle)
81   `(get-text-property 0 'buffer (car ,handle)))
82 (defmacro mm-handle-multipart-ctl-parameter (handle parameter)
83   `(get-text-property 0 ,parameter (car ,handle)))
84
85 (defmacro mm-make-handle (&optional buffer type encoding undisplayer
86                                     disposition description cache
87                                     id)
88   `(list ,buffer ,type ,encoding ,undisplayer
89          ,disposition ,description ,cache ,id))
90
91 (defcustom mm-inline-media-tests
92   '(("image/jpeg"
93      mm-inline-image
94      (lambda (handle)
95        (mm-valid-and-fit-image-p 'jpeg handle)))
96     ("image/png"
97      mm-inline-image
98      (lambda (handle)
99        (mm-valid-and-fit-image-p 'png handle)))
100     ("image/gif"
101      mm-inline-image
102      (lambda (handle)
103        (mm-valid-and-fit-image-p 'gif handle)))
104     ("image/tiff"
105      mm-inline-image
106      (lambda (handle)
107        (mm-valid-and-fit-image-p 'tiff handle)) )
108     ("image/xbm"
109      mm-inline-image
110      (lambda (handle)
111        (mm-valid-and-fit-image-p 'xbm handle)))
112     ("image/x-xbitmap"
113      mm-inline-image
114      (lambda (handle)
115        (mm-valid-and-fit-image-p 'xbm handle)))
116     ("image/xpm"
117      mm-inline-image
118      (lambda (handle)
119        (mm-valid-and-fit-image-p 'xpm handle)))
120     ("image/x-pixmap"
121      mm-inline-image
122      (lambda (handle)
123        (mm-valid-and-fit-image-p 'xpm handle)))
124     ("image/bmp"
125      mm-inline-image
126      (lambda (handle)
127        (mm-valid-and-fit-image-p 'bmp handle)))
128     ("text/plain" mm-inline-text identity)
129     ("text/enriched" mm-inline-text identity)
130     ("text/richtext" mm-inline-text identity)
131     ("text/x-patch" mm-display-patch-inline
132      (lambda (handle)
133        (locate-library "diff-mode")))
134     ("application/emacs-lisp" mm-display-elisp-inline identity)
135     ("text/html"
136      mm-inline-text
137      (lambda (handle)
138        (locate-library "w3")))
139     ("text/x-vcard"
140      mm-inline-text
141      (lambda (handle)
142        (or (featurep 'vcard)
143            (locate-library "vcard"))))
144     ("message/delivery-status" mm-inline-text identity)
145     ("message/rfc822" mm-inline-message identity)
146     ("message/partial" mm-inline-partial identity)
147     ("message/external-body" mm-inline-external-body identity)
148     ("text/.*" mm-inline-text identity)
149     ("audio/wav" mm-inline-audio
150      (lambda (handle)
151        (and (or (featurep 'nas-sound) (featurep 'native-sound))
152             (device-sound-enabled-p))))
153     ("audio/au"
154      mm-inline-audio
155      (lambda (handle)
156        (and (or (featurep 'nas-sound) (featurep 'native-sound))
157             (device-sound-enabled-p))))
158     ("application/pgp-signature" ignore identity)
159     ("application/x-pkcs7-signature" ignore identity)
160     ("application/pkcs7-signature" ignore identity)
161     ("multipart/alternative" ignore identity)
162     ("multipart/mixed" ignore identity)
163     ("multipart/related" ignore identity))
164   "Alist of media types/tests saying whether types can be displayed inline."
165   :type '(repeat (list (string :tag "MIME type")
166                        (function :tag "Display function")
167                        (function :tag "Display test")))
168   :group 'mime-display)
169
170 (defcustom mm-inlined-types
171   '("image/.*" "text/.*" "message/delivery-status" "message/rfc822"
172     "message/partial" "message/external-body" "application/emacs-lisp"
173     "application/pgp-signature" "application/x-pkcs7-signature"
174     "application/pkcs7-signature")
175   "List of media types that are to be displayed inline."
176   :type '(repeat string)
177   :group 'mime-display)
178   
179 (defcustom mm-automatic-display
180   '("text/plain" "text/enriched" "text/richtext" "text/html"
181     "text/x-vcard" "image/.*" "message/delivery-status" "multipart/.*"
182     "message/rfc822" "text/x-patch" "application/pgp-signature"
183     "application/emacs-lisp" "application/x-pkcs7-signature"
184     "application/pkcs7-signature")
185   "A list of MIME types to be displayed automatically."
186   :type '(repeat string)
187   :group 'mime-display)
188
189 (defcustom mm-attachment-override-types '("text/x-vcard")
190   "Types to have \"attachment\" ignored if they can be displayed inline."
191   :type '(repeat string)
192   :group 'mime-display)
193
194 (defcustom mm-inline-override-types nil
195   "Types to be treated as attachments even if they can be displayed inline."
196   :type '(repeat string)
197   :group 'mime-display)
198
199 (defcustom mm-automatic-external-display nil
200   "List of MIME type regexps that will be displayed externally automatically."
201   :type '(repeat string)
202   :group 'mime-display)
203
204 (defcustom mm-discouraged-alternatives nil
205   "List of MIME types that are discouraged when viewing multipart/alternative.
206 Viewing agents are supposed to view the last possible part of a message,
207 as that is supposed to be the richest.  However, users may prefer other
208 types instead, and this list says what types are most unwanted.  If,
209 for instance, text/html parts are very unwanted, and text/richtext are
210 somewhat unwanted, then the value of this variable should be set
211 to:
212
213  (\"text/html\" \"text/richtext\")"
214   :type '(repeat string)
215   :group 'mime-display)
216
217 (defvar mm-tmp-directory
218   (cond ((fboundp 'temp-directory) (temp-directory))
219         ((boundp 'temporary-file-directory) temporary-file-directory)
220         ("/tmp/"))
221   "Where mm will store its temporary files.")
222
223 (defcustom mm-inline-large-images nil
224   "If non-nil, then all images fit in the buffer."
225   :type 'boolean
226   :group 'mime-display)
227
228 ;;; Internal variables.
229
230 (defvar mm-dissection-list nil)
231 (defvar mm-last-shell-command "")
232 (defvar mm-content-id-alist nil)
233
234 ;; According to RFC2046, in particular, in a digest, the default
235 ;; Content-Type value for a body part is changed from "text/plain" to
236 ;; "message/rfc822".
237 (defvar mm-dissect-default-type "text/plain")
238
239 (autoload 'mml2015-verify "mml2015")
240 (autoload 'mml2015-verify-test "mml2015")
241 (autoload 'mml-smime-verify "mml-smime")
242 (autoload 'mml-smime-verify-test "mml-smime")
243
244 (defvar mm-verify-function-alist
245   '(("application/pgp-signature" mml2015-verify "PGP" mml2015-verify-test)
246     ("application/x-gnus-pgp-signature" mm-uu-pgp-signed-extract-1 "PGP" 
247      mm-uu-pgp-signed-test)
248     ("application/pkcs7-signature" mml-smime-verify "S/MIME" 
249      mml-smime-verify-test)
250     ("application/x-pkcs7-signature" mml-smime-verify "S/MIME" 
251      mml-smime-verify-test)))
252
253 (defcustom mm-verify-option 'never
254   "Option of verifying signed parts.
255 `never', not verify; `always', always verify; 
256 `known', only verify known protocols. Otherwise, ask user."
257   :type '(choice (item always)
258                  (item never)
259                  (item :tag "only known protocols" known)
260                  (item :tag "ask" nil))
261   :group 'mime-security)
262
263 (autoload 'mml2015-decrypt "mml2015")
264 (autoload 'mml2015-decrypt-test "mml2015")
265
266 (defvar mm-decrypt-function-alist
267   '(("application/pgp-encrypted" mml2015-decrypt "PGP" mml2015-decrypt-test)
268     ("application/x-gnus-pgp-encrypted" mm-uu-pgp-encrypted-extract-1 "PGP" 
269      mm-uu-pgp-encrypted-test)))
270
271 (defcustom mm-decrypt-option nil
272   "Option of decrypting encrypted parts.
273 `never', not decrypt; `always', always decrypt; 
274 `known', only decrypt known protocols. Otherwise, ask user."
275   :type '(choice (item always)
276                  (item never)
277                  (item :tag "only known protocols" known)
278                  (item :tag "ask" nil))
279   :group 'mime-security)
280
281 (defvar mm-viewer-completion-map
282   (let ((map (make-sparse-keymap 'mm-viewer-completion-map)))
283     (set-keymap-parent map minibuffer-local-completion-map)
284     map)
285   "Keymap for input viewer with completion.")
286
287 ;; Should we bind other key to minibuffer-complete-word?
288 (define-key mm-viewer-completion-map " " 'self-insert-command) 
289
290 ;;; The functions.
291
292 (defun mm-alist-to-plist (alist)
293   "Convert association list ALIST into the equivalent property-list form.
294 The plist is returned.  This converts from
295
296 \((a . 1) (b . 2) (c . 3))
297
298 into
299
300 \(a 1 b 2 c 3)
301
302 The original alist is not modified.  See also `destructive-alist-to-plist'."
303   (let (plist)
304     (while alist
305       (let ((el (car alist)))
306         (setq plist (cons (cdr el) (cons (car el) plist))))
307       (setq alist (cdr alist)))
308     (nreverse plist)))
309
310 (defun mm-dissect-buffer (&optional no-strict-mime)
311   "Dissect the current buffer and return a list of MIME handles."
312   (save-excursion
313     (let (ct ctl type subtype cte cd description id result)
314       (save-restriction
315         (mail-narrow-to-head)
316         (when (or no-strict-mime
317                   (mail-fetch-field "mime-version"))
318           (setq ct (mail-fetch-field "content-type")
319                 ctl (ignore-errors (mail-header-parse-content-type ct))
320                 cte (mail-fetch-field "content-transfer-encoding")
321                 cd (mail-fetch-field "content-disposition")
322                 description (mail-fetch-field "content-description")
323                 id (mail-fetch-field "content-id"))))
324       (when cte
325         (setq cte (mail-header-strip cte)))
326       (if (or (not ctl)
327               (not (string-match "/" (car ctl))))
328           (mm-dissect-singlepart
329            (list mm-dissect-default-type)
330            (and cte (intern (downcase (mail-header-remove-whitespace
331                                        (mail-header-remove-comments
332                                         cte)))))
333            no-strict-mime
334            (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
335            description)
336         (setq type (split-string (car ctl) "/"))
337         (setq subtype (cadr type)
338               type (pop type))
339         (setq
340          result
341          (cond
342           ((equal type "multipart")
343            (let ((mm-dissect-default-type (if (equal subtype "digest")
344                                               "message/rfc822"
345                                             "text/plain")))
346              (add-text-properties 0 (length (car ctl))
347                                   (mm-alist-to-plist (cdr ctl)) (car ctl))
348
349              ;; what really needs to be done here is a way to link a
350              ;; MIME handle back to it's parent MIME handle (in a multilevel
351              ;; MIME article).  That would probably require changing
352              ;; the mm-handle API so we simply store the multipart buffert
353              ;; name as a text property of the "multipart/whatever" string.
354              (add-text-properties 0 (length (car ctl))
355                                   (list 'buffer (mm-copy-to-buffer))
356                                   (car ctl))
357              (cons (car ctl) (mm-dissect-multipart ctl))))
358           (t
359            (mm-dissect-singlepart
360             ctl
361             (and cte (intern (downcase (mail-header-remove-whitespace
362                                         (mail-header-remove-comments
363                                          cte)))))
364             no-strict-mime
365             (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
366             description id))))
367         (when id
368           (when (string-match " *<\\(.*\\)> *" id)
369             (setq id (match-string 1 id)))
370           (push (cons id result) mm-content-id-alist))
371         result))))
372
373 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
374   (when (or force
375             (if (equal "text/plain" (car ctl))
376                 (assoc 'format ctl)
377               t))
378     (let ((res (mm-make-handle
379                 (mm-copy-to-buffer) ctl cte nil cdl description nil id)))
380       (push (car res) mm-dissection-list)
381       res)))
382
383 (defun mm-remove-all-parts ()
384   "Remove all MIME handles."
385   (interactive)
386   (mapcar 'mm-remove-part mm-dissection-list)
387   (setq mm-dissection-list nil))
388
389 (defun mm-dissect-multipart (ctl)
390   (goto-char (point-min))
391   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
392          (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
393          start parts
394          (end (save-excursion
395                 (goto-char (point-max))
396                 (if (re-search-backward close-delimiter nil t)
397                     (match-beginning 0)
398                   (point-max)))))
399     (setq boundary (concat (regexp-quote boundary) "[ \t]*$"))
400     (while (re-search-forward boundary end t)
401       (goto-char (match-beginning 0))
402       (when start
403         (save-excursion
404           (save-restriction
405             (narrow-to-region start (point))
406             (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
407       (forward-line 2)
408       (setq start (point)))
409     (when start
410       (save-excursion
411         (save-restriction
412           (narrow-to-region start end)
413           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
414     (mm-possibly-verify-or-decrypt (nreverse parts) ctl)))
415
416 (defun mm-copy-to-buffer ()
417   "Copy the contents of the current buffer to a fresh buffer."
418   (save-excursion
419     (let ((obuf (current-buffer))
420           beg)
421       (goto-char (point-min))
422       (search-forward-regexp "^\n" nil t)
423       (setq beg (point))
424       (set-buffer (generate-new-buffer " *mm*"))
425       (insert-buffer-substring obuf beg)
426       (current-buffer))))
427
428 (defun mm-display-parts (handle &optional no-default)
429   (if (stringp (car handle))
430       (mapcar 'mm-display-parts (cdr handle))
431     (if (bufferp (car handle))
432         (save-restriction
433           (narrow-to-region (point) (point))
434           (mm-display-part handle)
435           (goto-char (point-max)))
436       (mapcar 'mm-display-parts handle))))
437
438 (defun mm-display-part (handle &optional no-default)
439   "Display the MIME part represented by HANDLE.
440 Returns nil if the part is removed; inline if displayed inline;
441 external if displayed external."
442   (save-excursion
443     (mailcap-parse-mailcaps)
444     (if (mm-handle-displayed-p handle)
445         (mm-remove-part handle)
446       (let* ((type (mm-handle-media-type handle))
447              (method (mailcap-mime-info type)))
448         (if (mm-inlined-p handle)
449             (progn
450               (forward-line 1)
451               (mm-display-inline handle)
452               'inline)
453           (when (or method
454                     (not no-default))
455             (if (and (not method)
456                      (equal "text" (car (split-string type))))
457                 (progn
458                   (forward-line 1)
459                   (mm-insert-inline handle (mm-get-part handle))
460                   'inline)
461               (mm-display-external
462                handle (or method 'mailcap-save-binary-file)))))))))
463
464 (defun mm-display-external (handle method)
465   "Display HANDLE using METHOD."
466   (let ((outbuf (current-buffer)))
467     (mm-with-unibyte-buffer
468       (if (functionp method)
469           (let ((cur (current-buffer)))
470             (if (eq method 'mailcap-save-binary-file)
471                 (progn
472                   (set-buffer (generate-new-buffer " *mm*"))
473                   (setq method nil))
474               (mm-insert-part handle)
475               (let ((win (get-buffer-window cur t)))
476                 (when win
477                   (select-window win)))
478               (switch-to-buffer (generate-new-buffer " *mm*")))
479             (buffer-disable-undo)
480             (mm-set-buffer-file-coding-system mm-binary-coding-system)
481             (insert-buffer-substring cur)
482             (goto-char (point-min))
483             (message "Viewing with %s" method)
484             (let ((mm (current-buffer))
485                   (non-viewer (assq 'non-viewer
486                                     (mailcap-mime-info
487                                      (mm-handle-media-type handle) t))))
488               (unwind-protect
489                   (if method
490                       (funcall method)
491                     (mm-save-part handle))
492                 (when (and (not non-viewer)
493                            method)
494                   (mm-handle-set-undisplayer handle mm)))))
495         ;; The function is a string to be executed.
496         (mm-insert-part handle)
497         (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
498                (filename (mail-content-type-get
499                           (mm-handle-disposition handle) 'filename))
500                (mime-info (mailcap-mime-info
501                            (mm-handle-media-type handle) t))
502                (needsterm (or (assoc "needsterm" mime-info)
503                               (assoc "needsterminal" mime-info)))
504                (copiousoutput (assoc "copiousoutput" mime-info))
505                file buffer)
506           ;; We create a private sub-directory where we store our files.
507           (make-directory dir)
508           (set-file-modes dir 448)
509           (if filename
510               (setq file (expand-file-name (file-name-nondirectory filename)
511                                            dir))
512             (setq file (make-temp-name (expand-file-name "mm." dir))))
513           (let ((coding-system-for-write mm-binary-coding-system))
514             (write-region (point-min) (point-max) file nil 'nomesg))
515           (message "Viewing with %s" method)
516           (cond (needsterm
517                  (unwind-protect
518                      (start-process "*display*" nil
519                                     "xterm"
520                                     "-e" shell-file-name
521                                     shell-command-switch
522                                     (mm-mailcap-command
523                                      method file (mm-handle-type handle)))
524                    (mm-handle-set-undisplayer handle (cons file buffer)))
525                  (message "Displaying %s..." (format method file))
526                  'external)
527                 (copiousoutput
528                  (with-current-buffer outbuf
529                    (forward-line 1)
530                    (mm-insert-inline
531                     handle
532                     (unwind-protect
533                         (progn
534                           (call-process shell-file-name nil
535                                         (setq buffer
536                                               (generate-new-buffer " *mm*"))
537                                         nil
538                                         shell-command-switch
539                                         (mm-mailcap-command
540                                          method file (mm-handle-type handle)))
541                           (if (buffer-live-p buffer)
542                               (save-excursion
543                                 (set-buffer buffer)
544                                 (buffer-string))))
545                       (progn
546                         (ignore-errors (delete-file file))
547                         (ignore-errors (delete-directory
548                                         (file-name-directory file)))
549                         (ignore-errors (kill-buffer buffer))))))
550                  'inline)
551                 (t
552                  (unwind-protect
553                      (start-process "*display*"
554                                     (setq buffer
555                                           (generate-new-buffer " *mm*"))
556                                     shell-file-name
557                                     shell-command-switch
558                                     (mm-mailcap-command
559                                      method file (mm-handle-type handle)))
560                    (mm-handle-set-undisplayer handle (cons file buffer)))
561                  (message "Displaying %s..." (format method file))
562                  'external)))))))
563   
564 (defun mm-mailcap-command (method file type-list)
565   (let ((ctl (cdr type-list))
566         (beg 0)
567         (uses-stdin t)
568         out sub total)
569     (while (string-match "%{\\([^}]+\\)}\\|%s\\|%t\\|%%" method beg)
570       (push (substring method beg (match-beginning 0)) out)
571       (setq beg (match-end 0)
572             total (match-string 0 method)
573             sub (match-string 1 method))
574       (cond
575        ((string= total "%%")
576         (push "%" out))
577        ((string= total "%s")
578         (setq uses-stdin nil)
579         (push (mm-quote-arg file) out))
580        ((string= total "%t")
581         (push (mm-quote-arg (car type-list)) out))
582        (t
583         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
584     (push (substring method beg (length method)) out)
585     (if uses-stdin
586         (progn
587           (push "<" out)
588           (push (mm-quote-arg file) out)))
589     (mapconcat 'identity (nreverse out) "")))
590
591 (defun mm-remove-parts (handles)
592   "Remove the displayed MIME parts represented by HANDLES."
593   (if (and (listp handles)
594            (bufferp (car handles)))
595       (mm-remove-part handles)
596     (let (handle)
597       (while (setq handle (pop handles))
598         (cond
599          ((stringp handle)
600           (when (buffer-live-p (get-text-property 0 'buffer handle))
601             (kill-buffer (get-text-property 0 'buffer handle))))
602          ((and (listp handle)
603                (stringp (car handle)))
604           (mm-remove-parts (cdr handle)))
605          (t
606           (mm-remove-part handle)))))))
607
608 (defun mm-destroy-parts (handles)
609   "Remove the displayed MIME parts represented by HANDLES."
610   (if (and (listp handles)
611            (bufferp (car handles)))
612       (mm-destroy-part handles)
613     (let (handle)
614       (while (setq handle (pop handles))
615         (cond
616          ((stringp handle)
617           (when (buffer-live-p (get-text-property 0 'buffer handle))
618             (kill-buffer (get-text-property 0 'buffer handle))))
619          ((and (listp handle)
620                (stringp (car handle)))
621           (mm-destroy-parts handle))
622          (t
623           (mm-destroy-part handle)))))))
624
625 (defun mm-remove-part (handle)
626   "Remove the displayed MIME part represented by HANDLE."
627   (when (listp handle)
628     (let ((object (mm-handle-undisplayer handle)))
629       (ignore-errors
630         (cond
631          ;; Internally displayed part.
632          ((mm-annotationp object)
633           (delete-annotation object))
634          ((or (functionp object)
635               (and (listp object)
636                    (eq (car object) 'lambda)))
637           (funcall object))
638          ;; Externally displayed part.
639          ((consp object)
640           (ignore-errors (delete-file (car object)))
641           (ignore-errors (delete-directory (file-name-directory (car object))))
642           (ignore-errors (kill-buffer (cdr object))))
643          ((bufferp object)
644           (when (buffer-live-p object)
645             (kill-buffer object)))))
646       (mm-handle-set-undisplayer handle nil))))
647
648 (defun mm-display-inline (handle)
649   (let* ((type (mm-handle-media-type handle))
650          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
651     (funcall function handle)
652     (goto-char (point-min))))
653
654 (defun mm-assoc-string-match (alist type)
655   (dolist (elem alist)
656     (when (string-match (car elem) type)
657       (return elem))))
658
659 (defun mm-inlinable-p (handle)
660   "Say whether HANDLE can be displayed inline."
661   (let ((alist mm-inline-media-tests)
662         (type (mm-handle-media-type handle))
663         test)
664     (while alist
665       (when (string-match (caar alist) type)
666         (setq test (caddar alist)
667               alist nil)
668         (setq test (funcall test handle)))
669       (pop alist))
670     test))
671
672 (defun mm-automatic-display-p (handle)
673   "Say whether the user wants HANDLE to be displayed automatically."
674   (let ((methods mm-automatic-display)
675         (type (mm-handle-media-type handle))
676         method result)
677     (while (setq method (pop methods))
678       (when (and (not (mm-inline-override-p handle))
679                  (string-match method type)
680                  (mm-inlinable-p handle))
681         (setq result t
682               methods nil)))
683     result))
684
685 (defun mm-inlined-p (handle)
686   "Say whether the user wants HANDLE to be displayed automatically."
687   (let ((methods mm-inlined-types)
688         (type (mm-handle-media-type handle))
689         method result)
690     (while (setq method (pop methods))
691       (when (and (not (mm-inline-override-p handle))
692                  (string-match method type)
693                  (mm-inlinable-p handle))
694         (setq result t
695               methods nil)))
696     result))
697
698 (defun mm-attachment-override-p (handle)
699   "Say whether HANDLE should have attachment behavior overridden."
700   (let ((types mm-attachment-override-types)
701         (type (mm-handle-media-type handle))
702         ty)
703     (catch 'found
704       (while (setq ty (pop types))
705         (when (and (string-match ty type)
706                    (mm-inlinable-p handle))
707           (throw 'found t))))))
708
709 (defun mm-inline-override-p (handle)
710   "Say whether HANDLE should have inline behavior overridden."
711   (let ((types mm-inline-override-types)
712         (type (mm-handle-media-type handle))
713         ty)
714     (catch 'found
715       (while (setq ty (pop types))
716         (when (string-match ty type)
717           (throw 'found t))))))
718
719 (defun mm-automatic-external-display-p (type)
720   "Return the user-defined method for TYPE."
721   (let ((methods mm-automatic-external-display)
722         method result)
723     (while (setq method (pop methods))
724       (when (string-match method type)
725         (setq result t
726               methods nil)))
727     result))
728
729 (defun mm-destroy-part (handle)
730   "Destroy the data structures connected to HANDLE."
731   (when (listp handle)
732     (mm-remove-part handle)
733     (when (buffer-live-p (mm-handle-buffer handle))
734       (kill-buffer (mm-handle-buffer handle)))))
735
736 (defun mm-handle-displayed-p (handle)
737   "Say whether HANDLE is displayed or not."
738   (mm-handle-undisplayer handle))
739
740 ;;;
741 ;;; Functions for outputting parts
742 ;;;
743
744 (defun mm-get-part (handle)
745   "Return the contents of HANDLE as a string."
746   (mm-with-unibyte-buffer
747     (insert (with-current-buffer (mm-handle-buffer handle)
748               (mm-with-unibyte-current-buffer-mule4
749                 (buffer-string))))
750     (mm-decode-content-transfer-encoding
751      (mm-handle-encoding handle)
752      (mm-handle-media-type handle))
753     (buffer-string)))
754
755 (defun mm-insert-part (handle)
756   "Insert the contents of HANDLE in the current buffer."
757   (let ((cur (current-buffer)))
758     (save-excursion
759       (if (member (mm-handle-media-supertype handle) '("text" "message"))
760           (with-temp-buffer
761             (insert-buffer-substring (mm-handle-buffer handle))
762             (mm-decode-content-transfer-encoding
763              (mm-handle-encoding handle)
764              (mm-handle-media-type handle))
765             (let ((temp (current-buffer)))
766               (set-buffer cur)
767               (insert-buffer-substring temp)))
768         (mm-with-unibyte-buffer
769           (insert-buffer-substring (mm-handle-buffer handle))
770           (mm-decode-content-transfer-encoding
771            (mm-handle-encoding handle)
772            (mm-handle-media-type handle))
773           (let ((temp (current-buffer)))
774             (set-buffer cur)
775             (insert-buffer-substring temp)))))))
776
777 (defvar mm-default-directory nil)
778
779 (defun mm-save-part (handle)
780   "Write HANDLE to a file."
781   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
782          (filename (mail-content-type-get
783                     (mm-handle-disposition handle) 'filename))
784          file)
785     (when filename
786       (setq filename (file-name-nondirectory filename)))
787     (setq file
788           (read-file-name "Save MIME part to: "
789                           (expand-file-name
790                            (or filename name "")
791                            (or mm-default-directory default-directory))))
792     (setq mm-default-directory (file-name-directory file))
793     (and (or (not (file-exists-p file))
794              (yes-or-no-p (format "File %s already exists; overwrite? "
795                                   file)))
796          (progn
797            (mm-save-part-to-file handle file)
798            file))))
799
800 (defun mm-save-part-to-file (handle file)
801   (mm-with-unibyte-buffer
802     (mm-insert-part handle)
803     (let ((coding-system-for-write 'binary)
804           ;; Don't re-compress .gz & al.  Arguably we should make
805           ;; `file-name-handler-alist' nil, but that would chop
806           ;; ange-ftp, which is reasonable to use here.
807           (inhibit-file-name-operation 'write-region)
808           (inhibit-file-name-handlers
809            (cons 'jka-compr-handler inhibit-file-name-handlers)))
810       (write-region (point-min) (point-max) file))))
811
812 (defun mm-pipe-part (handle)
813   "Pipe HANDLE to a process."
814   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
815          (command
816           (read-string "Shell command on MIME part: " mm-last-shell-command)))
817     (mm-with-unibyte-buffer
818       (mm-insert-part handle)
819       (shell-command-on-region (point-min) (point-max) command nil))))
820
821 (defun mm-interactively-view-part (handle)
822   "Display HANDLE using METHOD."
823   (let* ((type (mm-handle-media-type handle))
824          (methods
825           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
826                   (mailcap-mime-info type 'all)))
827          (method (let ((minibuffer-local-completion-map
828                         mm-viewer-completion-map))
829                    (completing-read "Viewer: " methods))))
830     (when (string= method "")
831       (error "No method given"))
832     (if (string-match "^[^% \t]+$" method) 
833         (setq method (concat method " %s")))
834     (mm-display-external (copy-sequence handle) method)))
835
836 (defun mm-preferred-alternative (handles &optional preferred)
837   "Say which of HANDLES are preferred."
838   (let ((prec (if preferred (list preferred)
839                 (mm-preferred-alternative-precedence handles)))
840         p h result type handle)
841     (while (setq p (pop prec))
842       (setq h handles)
843       (while h
844         (setq handle (car h))
845         (setq type (mm-handle-media-type handle))
846         (when (and (equal p type)
847                    (mm-automatic-display-p handle)
848                    (or (stringp (car handle))
849                        (not (mm-handle-disposition handle))
850                        (equal (car (mm-handle-disposition handle))
851                               "inline")))
852           (setq result handle
853                 h nil
854                 prec nil))
855         (pop h)))
856     result))
857
858 (defun mm-preferred-alternative-precedence (handles)
859   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
860   (let ((seq (nreverse (mapcar #'mm-handle-media-type
861                                handles))))
862     (dolist (disc (reverse mm-discouraged-alternatives))
863       (dolist (elem (copy-sequence seq))
864         (when (string-match disc elem)
865           (setq seq (nconc (delete elem seq) (list elem))))))
866     seq))
867
868 (defun mm-get-content-id (id)
869   "Return the handle(s) referred to by ID."
870   (cdr (assoc id mm-content-id-alist)))
871
872 (defun mm-get-image (handle)
873   "Return an image instance based on HANDLE."
874   (let ((type (mm-handle-media-subtype handle))
875         spec)
876     ;; Allow some common translations.
877     (setq type
878           (cond
879            ((equal type "x-pixmap")
880             "xpm")
881            ((equal type "x-xbitmap")
882             "xbm")
883            (t type)))
884     (or (mm-handle-cache handle)
885         (mm-with-unibyte-buffer
886           (mm-insert-part handle)
887           (prog1
888               (setq spec
889                     (ignore-errors
890                      ;; Avoid testing `make-glyph' since W3 may define
891                      ;; a bogus version of it.
892                       (if (fboundp 'create-image)
893                           (create-image (buffer-string) (intern type) 'data-p)
894                         (cond
895                          ((equal type "xbm")
896                           ;; xbm images require special handling, since
897                           ;; the only way to create glyphs from these
898                           ;; (without a ton of work) is to write them
899                           ;; out to a file, and then create a file
900                           ;; specifier.
901                           (let ((file (make-temp-name
902                                        (expand-file-name "emm.xbm"
903                                                          mm-tmp-directory))))
904                             (unwind-protect
905                                 (progn
906                                   (write-region (point-min) (point-max) file)
907                                   (make-glyph (list (cons 'x file))))
908                               (ignore-errors
909                                (delete-file file)))))
910                          (t
911                           (make-glyph
912                            (vector (intern type) :data (buffer-string))))))))
913             (mm-handle-set-cache handle spec))))))
914
915 (defun mm-image-fit-p (handle)
916   "Say whether the image in HANDLE will fit the current window."
917   (let ((image (mm-get-image handle)))
918     (if (fboundp 'glyph-width)
919         ;; XEmacs' glyphs can actually tell us about their width, so
920         ;; lets be nice and smart about them.
921         (or mm-inline-large-images
922             (and (< (glyph-width image) (window-pixel-width))
923                  (< (glyph-height image) (window-pixel-height))))
924       (let* ((size (image-size image))
925              (w (car size))
926              (h (cdr size)))
927         (or mm-inline-large-images
928             (and (< h (1- (window-height))) ; Don't include mode line.
929                  (< w (window-width))))))))
930
931 (defun mm-valid-image-format-p (format)
932   "Say whether FORMAT can be displayed natively by Emacs."
933   (cond
934    ;; Handle XEmacs
935    ((fboundp 'valid-image-instantiator-format-p)
936     (valid-image-instantiator-format-p format))
937    ;; Handle Emacs 21
938    ((fboundp 'image-type-available-p)
939     (and (display-graphic-p)
940          (image-type-available-p format)))
941    ;; Nobody else can do images yet.
942    (t
943     nil)))
944
945 (defun mm-valid-and-fit-image-p (format handle)
946   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
947   (and (mm-valid-image-format-p format)
948        (mm-image-fit-p handle)))
949
950 (defun mm-find-part-by-type (handles type &optional notp recursive) 
951   "Search in HANDLES for part with TYPE.
952 If NOTP, returns first non-matching part.
953 If RECURSIVE, search recursively."
954   (let (handle)
955     (while handles
956       (if (and recursive (stringp (caar handles)))
957           (if (setq handle (mm-find-part-by-type (cdar handles) type
958                                                  notp recursive))
959               (setq handles nil))
960         (if (if notp
961                 (not (equal (mm-handle-media-type (car handles)) type))
962               (equal (mm-handle-media-type (car handles)) type))
963             (setq handle (car handles)
964                   handles nil)))
965       (setq handles (cdr handles)))
966     handle))
967
968 (defun mm-find-raw-part-by-type (ctl type &optional notp) 
969   (goto-char (point-min))
970   (let* ((boundary (concat "--" (mm-handle-multipart-ctl-parameter ctl 
971                                                                    'boundary)))
972          (close-delimiter (concat "^" (regexp-quote boundary) "--[ \t]*$"))
973          start
974          (end (save-excursion
975                 (goto-char (point-max))
976                 (if (re-search-backward close-delimiter nil t)
977                     (match-beginning 0)
978                   (point-max))))
979          result)
980     (setq boundary (concat "^" (regexp-quote boundary) "[ \t]*$"))
981     (while (and (not result)
982                 (re-search-forward boundary end t))
983       (goto-char (match-beginning 0))
984       (when start
985         (save-excursion
986           (save-restriction
987             (narrow-to-region start (1- (point)))
988             (when (let ((ctl (ignore-errors 
989                                (mail-header-parse-content-type 
990                                 (mail-fetch-field "content-type")))))
991                     (if notp
992                         (not (equal (car ctl) type))
993                       (equal (car ctl) type)))
994               (setq result (buffer-substring (point-min) (point-max)))))))
995       (forward-line 1)
996       (setq start (point)))
997     (when (and (not result) start)
998       (save-excursion
999         (save-restriction
1000           (narrow-to-region start end)
1001           (when (let ((ctl (ignore-errors 
1002                              (mail-header-parse-content-type 
1003                               (mail-fetch-field "content-type")))))
1004                   (if notp
1005                       (not (equal (car ctl) type))
1006                     (equal (car ctl) type)))
1007             (setq result (buffer-substring (point-min) (point-max)))))))
1008     result))
1009
1010 (defvar mm-security-handle nil)
1011
1012 (defsubst mm-set-handle-multipart-parameter (handle parameter value)
1013   ;; HANDLE could be a CTL.
1014   (if handle
1015       (put-text-property 0 (length (car handle)) parameter value 
1016                          (car handle))))
1017
1018 (defun mm-possibly-verify-or-decrypt (parts ctl)
1019   (let ((subtype (cadr (split-string (car ctl) "/")))
1020         (mm-security-handle ctl) ;; (car CTL) is the type.
1021         (from (save-restriction
1022                 (mail-narrow-to-head)
1023                 (cadr (funcall gnus-extract-address-components 
1024                                (or (mail-fetch-field "from") "")))))
1025         protocol func functest)
1026     (cond 
1027      ((equal subtype "signed")
1028       (unless (and (setq protocol 
1029                          (mm-handle-multipart-ctl-parameter ctl 'protocol))
1030                    (not (equal protocol "multipart/mixed")))
1031         ;; The message is broken or draft-ietf-openpgp-multsig-01.
1032         (let ((protocols mm-verify-function-alist))
1033           (while protocols
1034             (if (and (or (not (setq functest (nth 3 (car protocols))))
1035                          (funcall functest parts ctl))
1036                      (mm-find-part-by-type parts (caar protocols) nil t))
1037                 (setq protocol (caar protocols)
1038                       protocols nil)
1039               (setq protocols (cdr protocols))))))
1040       (setq func (nth 1 (assoc protocol mm-verify-function-alist)))
1041       (if (cond
1042            ((eq mm-verify-option 'never) nil)
1043            ((eq mm-verify-option 'always) t)
1044            ((eq mm-verify-option 'known) 
1045             (and func 
1046                  (or (not (setq functest 
1047                                 (nth 3 (assoc protocol 
1048                                               mm-verify-function-alist))))
1049                      (funcall functest parts ctl))))
1050            (t (y-or-n-p
1051                (format "Verify signed (%s) part? "
1052                        (or (nth 2 (assoc protocol mm-verify-function-alist))
1053                            (format "protocol=%s" protocol))))))
1054           (save-excursion
1055             (if func
1056                 (funcall func parts ctl)
1057               (mm-set-handle-multipart-parameter 
1058                mm-security-handle 'gnus-details 
1059                (format "Unknown sign protocol (%s)" protocol))))))
1060      ((equal subtype "encrypted")
1061       (unless (setq protocol 
1062                     (mm-handle-multipart-ctl-parameter ctl 'protocol))
1063         ;; The message is broken.
1064         (let ((parts parts))
1065           (while parts
1066             (if (assoc (mm-handle-media-type (car parts)) 
1067                        mm-decrypt-function-alist)
1068                 (setq protocol (mm-handle-media-type (car parts))
1069                       parts nil)
1070               (setq parts (cdr parts))))))
1071       (setq func (nth 1 (assoc protocol mm-decrypt-function-alist)))
1072       (if (cond
1073            ((eq mm-decrypt-option 'never) nil)
1074            ((eq mm-decrypt-option 'always) t)
1075            ((eq mm-decrypt-option 'known)
1076             (and func 
1077                  (or (not (setq functest 
1078                                 (nth 3 (assoc protocol 
1079                                               mm-decrypt-function-alist))))
1080                      (funcall functest parts ctl))))
1081            (t (y-or-n-p 
1082                (format "Decrypt (%s) part? "
1083                        (or (nth 2 (assoc protocol mm-decrypt-function-alist))
1084                            (format "protocol=%s" protocol))))))
1085           (save-excursion
1086             (if func
1087                 (setq parts (funcall func parts ctl))
1088               (mm-set-handle-multipart-parameter 
1089                mm-security-handle 'gnus-details 
1090                (format "Unknown encrypt protocol (%s)" protocol))))))
1091      (t nil))
1092     parts))
1093
1094 (provide 'mm-decode)
1095
1096 ;;; mm-decode.el ends here