Use macro from w3. For details see ChangeLog.
[gnus] / lisp / mm-decode.el
1 ;;; mm-decode.el --- Functions for decoding MIME things
2 ;; Copyright (C) 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 (require 'mail-parse)
28 (require 'mailcap)
29 (require 'mm-bodies)
30 (eval-when-compile (require 'cl))
31
32 (eval-and-compile
33   (autoload 'mm-inline-partial "mm-partial"))
34
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             (message "Viewing with %s" method)
372             (let ((mm (current-buffer))
373                   (non-viewer (assq 'non-viewer
374                                     (mailcap-mime-info
375                                      (mm-handle-media-type handle) t))))
376               (unwind-protect
377                   (if method
378                       (funcall method)
379                     (mm-save-part handle))
380                 (when (and (not non-viewer)
381                            method)
382                   (mm-handle-set-undisplayer handle mm)))))
383         ;; The function is a string to be executed.
384         (mm-insert-part handle)
385         (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
386                (filename (mail-content-type-get
387                           (mm-handle-disposition handle) 'filename))
388                (mime-info (mailcap-mime-info
389                            (mm-handle-media-type handle) t))
390                (needsterm (or (assoc "needsterm" mime-info)
391                               (assoc "needsterminal" mime-info)))
392                (copiousoutput (assoc "copiousoutput" mime-info))
393                file buffer)
394           ;; We create a private sub-directory where we store our files.
395           (make-directory dir)
396           (set-file-modes dir 448)
397           (if filename
398               (setq file (expand-file-name (file-name-nondirectory filename)
399                                            dir))
400             (setq file (make-temp-name (expand-file-name "mm." dir))))
401           (let ((coding-system-for-write mm-binary-coding-system))
402             (write-region (point-min) (point-max) file nil 'nomesg))
403           (message "Viewing with %s" method)
404           (cond (needsterm
405                  (unwind-protect
406                      (start-process "*display*" nil
407                                     "xterm"
408                                     "-e" shell-file-name
409                                     shell-command-switch
410                                     (mm-mailcap-command
411                                      method file (mm-handle-type handle)))
412                    (mm-handle-set-undisplayer handle (cons file buffer)))
413                  (message "Displaying %s..." (format method file))
414                  'external)
415                 (copiousoutput
416                  (with-current-buffer outbuf
417                    (forward-line 1)
418                    (mm-insert-inline
419                     handle
420                     (unwind-protect
421                         (progn
422                           (call-process shell-file-name nil
423                                         (setq buffer
424                                               (generate-new-buffer "*mm*"))
425                                         nil
426                                         shell-command-switch
427                                         (mm-mailcap-command
428                                          method file (mm-handle-type handle)))
429                           (if (buffer-live-p buffer)
430                               (save-excursion
431                                 (set-buffer buffer)
432                                 (buffer-string))))
433                       (progn
434                         (ignore-errors (delete-file file))
435                         (ignore-errors (delete-directory
436                                         (file-name-directory file)))
437                         (ignore-errors (kill-buffer buffer))))))
438                  'inline)
439                 (t
440                  (unwind-protect
441                      (start-process "*display*"
442                                     (setq buffer
443                                           (generate-new-buffer "*mm*"))
444                                     shell-file-name
445                                     shell-command-switch
446                                     (mm-mailcap-command
447                                      method file (mm-handle-type handle)))
448                    (mm-handle-set-undisplayer handle (cons file buffer)))
449                  (message "Displaying %s..." (format method file))
450                  'external)))))))
451   
452 (defun mm-mailcap-command (method file type-list)
453   (let ((ctl (cdr type-list))
454         (beg 0)
455         (uses-stdin t)
456         out sub total)
457     (while (string-match "%{\\([^}]+\\)}\\|%s\\|%t\\|%%" method beg)
458       (push (substring method beg (match-beginning 0)) out)
459       (setq beg (match-end 0)
460             total (match-string 0 method)
461             sub (match-string 1 method))
462       (cond
463        ((string= total "%%")
464         (push "%" out))
465        ((string= total "%s")
466         (setq uses-stdin nil)
467         (push (mm-quote-arg file) out))
468        ((string= total "%t")
469         (push (mm-quote-arg (car type-list)) out))
470        (t
471         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
472     (push (substring method beg (length method)) out)
473     (if uses-stdin
474         (progn
475           (push "<" out)
476           (push (mm-quote-arg file) out)))
477     (mapconcat 'identity (nreverse out) "")))
478     
479 (defun mm-remove-parts (handles)
480   "Remove the displayed MIME parts represented by HANDLES."
481   (if (and (listp handles)
482            (bufferp (car handles)))
483       (mm-remove-part handles)
484     (let (handle)
485       (while (setq handle (pop handles))
486         (cond
487          ((stringp handle)
488           ;; Do nothing.
489           )
490          ((and (listp handle)
491                (stringp (car handle)))
492           (mm-remove-parts (cdr handle)))
493          (t
494           (mm-remove-part handle)))))))
495
496 (defun mm-destroy-parts (handles)
497   "Remove the displayed MIME parts represented by HANDLES."
498   (if (and (listp handles)
499            (bufferp (car handles)))
500       (mm-destroy-part handles)
501     (let (handle)
502       (while (setq handle (pop handles))
503         (cond
504          ((stringp handle)
505           ;; Do nothing.
506           )
507          ((and (listp handle)
508                (stringp (car handle)))
509           (mm-destroy-parts (cdr handle)))
510          (t
511           (mm-destroy-part handle)))))))
512
513 (defun mm-remove-part (handle)
514   "Remove the displayed MIME part represented by HANDLE."
515   (when (listp handle)
516     (let ((object (mm-handle-undisplayer handle)))
517       (ignore-errors
518         (cond
519          ;; Internally displayed part.
520          ((mm-annotationp object)
521           (delete-annotation object))
522          ((or (functionp object)
523               (and (listp object)
524                    (eq (car object) 'lambda)))
525           (funcall object))
526          ;; Externally displayed part.
527          ((consp object)
528           (ignore-errors (delete-file (car object)))
529           (ignore-errors (delete-directory (file-name-directory (car object))))
530           (ignore-errors (kill-buffer (cdr object))))
531          ((bufferp object)
532           (when (buffer-live-p object)
533             (kill-buffer object)))))
534       (mm-handle-set-undisplayer handle nil))))
535
536 (defun mm-display-inline (handle)
537   (let* ((type (mm-handle-media-type handle))
538          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
539     (funcall function handle)
540     (goto-char (point-min))))
541
542 (defun mm-assoc-string-match (alist type)
543   (dolist (elem alist)
544     (when (string-match (car elem) type)
545       (return elem))))
546
547 (defun mm-inlinable-p (handle)
548   "Say whether HANDLE can be displayed inline."
549   (let ((alist mm-inline-media-tests)
550         (type (mm-handle-media-type handle))
551         test)
552     (while alist
553       (when (string-match (caar alist) type)
554         (setq test (caddar alist)
555               alist nil)
556         (setq test (funcall test handle)))
557       (pop alist))
558     test))
559
560 (defun mm-automatic-display-p (handle)
561   "Say whether the user wants HANDLE to be displayed automatically."
562   (let ((methods mm-automatic-display)
563         (type (mm-handle-media-type handle))
564         method result)
565     (while (setq method (pop methods))
566       (when (and (not (mm-inline-override-p handle))
567                  (string-match method type)
568                  (mm-inlinable-p handle))
569         (setq result t
570               methods nil)))
571     result))
572
573 (defun mm-inlined-p (handle)
574   "Say whether the user wants HANDLE to be displayed automatically."
575   (let ((methods mm-inlined-types)
576         (type (mm-handle-media-type handle))
577         method result)
578     (while (setq method (pop methods))
579       (when (and (not (mm-inline-override-p handle))
580                  (string-match method type)
581                  (mm-inlinable-p handle))
582         (setq result t
583               methods nil)))
584     result))
585
586 (defun mm-attachment-override-p (handle)
587   "Say whether HANDLE should have attachment behavior overridden."
588   (let ((types mm-attachment-override-types)
589         (type (mm-handle-media-type handle))
590         ty)
591     (catch 'found
592       (while (setq ty (pop types))
593         (when (and (string-match ty type)
594                    (mm-inlinable-p handle))
595           (throw 'found t))))))
596
597 (defun mm-inline-override-p (handle)
598   "Say whether HANDLE should have inline behavior overridden."
599   (let ((types mm-inline-override-types)
600         (type (mm-handle-media-type handle))
601         ty)
602     (catch 'found
603       (while (setq ty (pop types))
604         (when (string-match ty type)
605           (throw 'found t))))))
606
607 (defun mm-automatic-external-display-p (type)
608   "Return the user-defined method for TYPE."
609   (let ((methods mm-automatic-external-display)
610         method result)
611     (while (setq method (pop methods))
612       (when (string-match method type)
613         (setq result t
614               methods nil)))
615     result))
616
617 (defun mm-destroy-part (handle)
618   "Destroy the data structures connected to HANDLE."
619   (when (listp handle)
620     (mm-remove-part handle)
621     (when (buffer-live-p (mm-handle-buffer handle))
622       (kill-buffer (mm-handle-buffer handle)))))
623
624 (defun mm-handle-displayed-p (handle)
625   "Say whether HANDLE is displayed or not."
626   (mm-handle-undisplayer handle))
627
628 ;;;
629 ;;; Functions for outputting parts
630 ;;;
631
632 (defun mm-get-part (handle)
633   "Return the contents of HANDLE as a string."
634   (mm-with-unibyte-buffer
635     (mm-insert-part handle)
636     (buffer-string)))
637
638 (defun mm-insert-part (handle)
639   "Insert the contents of HANDLE in the current buffer."
640   (let ((cur (current-buffer)))
641     (save-excursion
642       (if (member (mm-handle-media-supertype handle) '("text" "message"))
643           (with-temp-buffer
644             (insert-buffer-substring (mm-handle-buffer handle))
645             (mm-decode-content-transfer-encoding
646              (mm-handle-encoding handle)
647              (mm-handle-media-type handle))
648             (let ((temp (current-buffer)))
649               (set-buffer cur)
650               (insert-buffer-substring temp)))
651         (mm-with-unibyte-buffer
652           (insert-buffer-substring (mm-handle-buffer handle))
653           (mm-decode-content-transfer-encoding
654            (mm-handle-encoding handle)
655            (mm-handle-media-type handle))
656           (let ((temp (current-buffer)))
657             (set-buffer cur)
658             (insert-buffer-substring temp)))))))
659
660 (defvar mm-default-directory nil)
661
662 (defun mm-save-part (handle)
663   "Write HANDLE to a file."
664   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
665          (filename (mail-content-type-get
666                     (mm-handle-disposition handle) 'filename))
667          file)
668     (when filename
669       (setq filename (file-name-nondirectory filename)))
670     (setq file
671           (read-file-name "Save MIME part to: "
672                           (expand-file-name
673                            (or filename name "")
674                            (or mm-default-directory default-directory))))
675     (setq mm-default-directory (file-name-directory file))
676     (when (or (not (file-exists-p file))
677               (yes-or-no-p (format "File %s already exists; overwrite? "
678                                    file)))
679       (mm-save-part-to-file handle file))))
680
681 (defun mm-save-part-to-file (handle file)
682   (mm-with-unibyte-buffer
683     (mm-insert-part handle)
684     (let ((coding-system-for-write 'binary)
685           ;; Don't re-compress .gz & al.  Arguably we should make
686           ;; `file-name-handler-alist' nil, but that would chop
687           ;; ange-ftp, which is reasonable to use here.
688           (inhibit-file-name-operation 'write-region)
689           (inhibit-file-name-handlers
690            (cons 'jka-compr-handler inhibit-file-name-handlers)))
691       (write-region (point-min) (point-max) file))))
692
693 (defun mm-pipe-part (handle)
694   "Pipe HANDLE to a process."
695   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
696          (command
697           (read-string "Shell command on MIME part: " mm-last-shell-command)))
698     (mm-with-unibyte-buffer
699       (mm-insert-part handle)
700       (shell-command-on-region (point-min) (point-max) command nil))))
701
702 (defun mm-interactively-view-part (handle)
703   "Display HANDLE using METHOD."
704   (let* ((type (mm-handle-media-type handle))
705          (methods
706           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
707                   (mailcap-mime-info type 'all)))
708          (method (completing-read "Viewer: " methods)))
709     (when (string= method "")
710       (error "No method given"))
711     (if (string-match "^[^% \t]+$" method) 
712         (setq method (concat method " %s")))
713     (mm-display-external (copy-sequence handle) method)))
714
715 (defun mm-preferred-alternative (handles &optional preferred)
716   "Say which of HANDLES are preferred."
717   (let ((prec (if preferred (list preferred)
718                 (mm-preferred-alternative-precedence handles)))
719         p h result type handle)
720     (while (setq p (pop prec))
721       (setq h handles)
722       (while h
723         (setq handle (car h))
724         (setq type (mm-handle-media-type handle))
725         (when (and (equal p type)
726                    (mm-automatic-display-p handle)
727                    (or (stringp (car handle))
728                        (not (mm-handle-disposition handle))
729                        (equal (car (mm-handle-disposition handle))
730                               "inline")))
731           (setq result handle
732                 h nil
733                 prec nil))
734         (pop h)))
735     result))
736
737 (defun mm-preferred-alternative-precedence (handles)
738   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
739   (let ((seq (nreverse (mapcar #'mm-handle-media-type
740                                handles))))
741     (dolist (disc (reverse mm-discouraged-alternatives))
742       (dolist (elem (copy-sequence seq))
743         (when (string-match disc elem)
744           (setq seq (nconc (delete elem seq) (list elem))))))
745     seq))
746
747 (defun mm-get-content-id (id)
748   "Return the handle(s) referred to by ID."
749   (cdr (assoc id mm-content-id-alist)))
750
751 (defun mm-get-image (handle)
752   "Return an image instance based on HANDLE."
753   (let ((type (mm-handle-media-subtype handle))
754         spec)
755     ;; Allow some common translations.
756     (setq type
757           (cond
758            ((equal type "x-pixmap")
759             "xpm")
760            ((equal type "x-xbitmap")
761             "xbm")
762            (t type)))
763     (or (mm-handle-cache handle)
764         (mm-with-unibyte-buffer
765           (mm-insert-part handle)
766           (prog1
767               (setq spec
768                     (ignore-errors
769                       (if (fboundp 'make-glyph)
770                           (cond
771                            ((equal type "xbm")
772                             ;; xbm images require special handling, since
773                             ;; the only way to create glyphs from these
774                             ;; (without a ton of work) is to write them
775                             ;; out to a file, and then create a file
776                             ;; specifier.
777                             (let ((file (make-temp-name
778                                          (expand-file-name "emm.xbm"
779                                                            mm-tmp-directory))))
780                               (unwind-protect
781                                   (progn
782                                     (write-region (point-min) (point-max) file)
783                                     (make-glyph (list (cons 'x file))))
784                                 (ignore-errors
785                                   (delete-file file)))))
786                            (t
787                             (make-glyph
788                              (vector (intern type) :data (buffer-string)))))
789                         (create-image (buffer-string) (intern type) 'data-p))))
790             (mm-handle-set-cache handle spec))))))
791
792 (defun mm-image-fit-p (handle)
793   "Say whether the image in HANDLE will fit the current window."
794   (let ((image (mm-get-image handle)))
795     (if (fboundp 'glyph-width)
796         ;; XEmacs' glyphs can actually tell us about their width, so
797         ;; lets be nice and smart about them.
798         (or mm-inline-large-images
799             (and (< (glyph-width image) (window-pixel-width))
800                  (< (glyph-height image) (window-pixel-height))))
801       (let* ((size (image-size image))
802              (w (car size))
803              (h (cdr size)))
804         (or mm-inline-large-images
805             (and (< h (1- (window-height))) ; Don't include mode line.
806                  (< w (window-width))))))))
807
808 (defun mm-valid-image-format-p (format)
809   "Say whether FORMAT can be displayed natively by Emacs."
810   (cond
811    ;; Handle XEmacs
812    ((fboundp 'valid-image-instantiator-format-p)
813     (valid-image-instantiator-format-p format))
814    ;; Handle Emacs 21
815    ((fboundp 'image-type-available-p)
816     (and (display-graphic-p)
817          (image-type-available-p format)))
818    ;; Nobody else can do images yet.
819    (t
820     nil)))
821
822 (defun mm-valid-and-fit-image-p (format handle)
823   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
824   (and window-system
825        (mm-valid-image-format-p format)
826        (mm-image-fit-p handle)))
827
828 (provide 'mm-decode)
829
830 ;;; mm-decode.el ends here