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