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