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