Importing Gnus v5.8.7.
[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 '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     (while (search-forward boundary end t)
299       (goto-char (match-beginning 0))
300       (when start
301         (save-excursion
302           (save-restriction
303             (narrow-to-region start (point))
304             (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
305       (forward-line 2)
306       (setq start (point)))
307     (when start
308       (save-excursion
309         (save-restriction
310           (narrow-to-region start end)
311           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
312     (nreverse parts)))
313
314 (defun mm-copy-to-buffer ()
315   "Copy the contents of the current buffer to a fresh buffer."
316   (save-excursion
317     (let ((obuf (current-buffer))
318           beg)
319       (goto-char (point-min))
320       (search-forward-regexp "^\n" nil t)
321       (setq beg (point))
322       (set-buffer (generate-new-buffer " *mm*"))
323       (insert-buffer-substring obuf beg)
324       (current-buffer))))
325
326 (defun mm-display-part (handle &optional no-default)
327   "Display the MIME part represented by HANDLE.
328 Returns nil if the part is removed; inline if displayed inline;
329 external if displayed external."
330   (save-excursion
331     (mailcap-parse-mailcaps)
332     (if (mm-handle-displayed-p handle)
333         (mm-remove-part handle)
334       (let* ((type (mm-handle-media-type handle))
335              (method (mailcap-mime-info type)))
336         (if (mm-inlined-p handle)
337             (progn
338               (forward-line 1)
339               (mm-display-inline handle)
340               'inline)
341           (when (or method
342                     (not no-default))
343             (if (and (not method)
344                      (equal "text" (car (split-string type))))
345                 (progn
346                   (forward-line 1)
347                   (mm-insert-inline handle (mm-get-part handle))
348                   'inline)
349               (mm-display-external
350                handle (or method 'mailcap-save-binary-file)))))))))
351
352 (defun mm-display-external (handle method)
353   "Display HANDLE using METHOD."
354   (let ((outbuf (current-buffer)))
355     (mm-with-unibyte-buffer
356       (if (functionp method)
357           (let ((cur (current-buffer)))
358             (if (eq method 'mailcap-save-binary-file)
359                 (progn
360                   (set-buffer (generate-new-buffer "*mm*"))
361                   (setq method nil))
362               (mm-insert-part handle)
363               (let ((win (get-buffer-window cur t)))
364                 (when win
365                   (select-window win)))
366               (switch-to-buffer (generate-new-buffer "*mm*")))
367             (buffer-disable-undo)
368             (mm-set-buffer-file-coding-system mm-binary-coding-system)
369             (insert-buffer-substring cur)
370             (message "Viewing with %s" method)
371             (let ((mm (current-buffer))
372                   (non-viewer (assq 'non-viewer
373                                     (mailcap-mime-info
374                                      (mm-handle-media-type handle) t))))
375               (unwind-protect
376                   (if method
377                       (funcall method)
378                     (mm-save-part handle))
379                 (when (and (not non-viewer)
380                            method)
381                   (mm-handle-set-undisplayer handle mm)))))
382         ;; The function is a string to be executed.
383         (mm-insert-part handle)
384         (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
385                (filename (mail-content-type-get
386                           (mm-handle-disposition handle) 'filename))
387                (mime-info (mailcap-mime-info
388                            (mm-handle-media-type handle) t))
389                (needsterm (or (assoc "needsterm" mime-info)
390                               (assoc "needsterminal" mime-info)))
391                (copiousoutput (assoc "copiousoutput" mime-info))
392                file buffer)
393           ;; We create a private sub-directory where we store our files.
394           (make-directory dir)
395           (set-file-modes dir 448)
396           (if filename
397               (setq file (expand-file-name (file-name-nondirectory filename)
398                                            dir))
399             (setq file (make-temp-name (expand-file-name "mm." dir))))
400           (let ((coding-system-for-write mm-binary-coding-system))
401             (write-region (point-min) (point-max) file nil 'nomesg))
402           (message "Viewing with %s" method)
403           (cond (needsterm
404                  (unwind-protect
405                      (start-process "*display*" nil
406                                     "xterm"
407                                     "-e" shell-file-name
408                                     shell-command-switch
409                                     (mm-mailcap-command
410                                      method file (mm-handle-type handle)))
411                    (mm-handle-set-undisplayer handle (cons file buffer)))
412                  (message "Displaying %s..." (format method file))
413                  'external)
414                 (copiousoutput
415                  (with-current-buffer outbuf
416                    (forward-line 1)
417                    (mm-insert-inline
418                     handle
419                     (unwind-protect
420                         (progn
421                           (call-process shell-file-name nil
422                                         (setq buffer
423                                               (generate-new-buffer "*mm*"))
424                                         nil
425                                         shell-command-switch
426                                         (mm-mailcap-command
427                                          method file (mm-handle-type handle)))
428                           (if (buffer-live-p buffer)
429                               (save-excursion
430                                 (set-buffer buffer)
431                                 (buffer-string))))
432                       (progn
433                         (ignore-errors (delete-file file))
434                         (ignore-errors (delete-directory
435                                         (file-name-directory file)))
436                         (ignore-errors (kill-buffer buffer))))))
437                  'inline)
438                 (t
439                  (unwind-protect
440                      (start-process "*display*"
441                                     (setq buffer
442                                           (generate-new-buffer "*mm*"))
443                                     shell-file-name
444                                     shell-command-switch
445                                     (mm-mailcap-command
446                                      method file (mm-handle-type handle)))
447                    (mm-handle-set-undisplayer handle (cons file buffer)))
448                  (message "Displaying %s..." (format method file))
449                  'external)))))))
450   
451 (defun mm-mailcap-command (method file type-list)
452   (let ((ctl (cdr type-list))
453         (beg 0)
454         (uses-stdin t)
455         out sub total)
456     (while (string-match "%{\\([^}]+\\)}\\|%s\\|%t\\|%%" method beg)
457       (push (substring method beg (match-beginning 0)) out)
458       (setq beg (match-end 0)
459             total (match-string 0 method)
460             sub (match-string 1 method))
461       (cond
462        ((string= total "%%")
463         (push "%" out))
464        ((string= total "%s")
465         (setq uses-stdin nil)
466         (push (mm-quote-arg file) out))
467        ((string= total "%t")
468         (push (mm-quote-arg (car type-list)) out))
469        (t
470         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
471     (push (substring method beg (length method)) out)
472     (if uses-stdin
473         (progn
474           (push "<" out)
475           (push (mm-quote-arg file) out)))
476     (mapconcat 'identity (nreverse out) "")))
477     
478 (defun mm-remove-parts (handles)
479   "Remove the displayed MIME parts represented by HANDLES."
480   (if (and (listp handles)
481            (bufferp (car handles)))
482       (mm-remove-part handles)
483     (let (handle)
484       (while (setq handle (pop handles))
485         (cond
486          ((stringp handle)
487           ;; Do nothing.
488           )
489          ((and (listp handle)
490                (stringp (car handle)))
491           (mm-remove-parts (cdr handle)))
492          (t
493           (mm-remove-part handle)))))))
494
495 (defun mm-destroy-parts (handles)
496   "Remove the displayed MIME parts represented by HANDLES."
497   (if (and (listp handles)
498            (bufferp (car handles)))
499       (mm-destroy-part handles)
500     (let (handle)
501       (while (setq handle (pop handles))
502         (cond
503          ((stringp handle)
504           ;; Do nothing.
505           )
506          ((and (listp handle)
507                (stringp (car handle)))
508           (mm-destroy-parts (cdr handle)))
509          (t
510           (mm-destroy-part handle)))))))
511
512 (defun mm-remove-part (handle)
513   "Remove the displayed MIME part represented by HANDLE."
514   (when (listp handle)
515     (let ((object (mm-handle-undisplayer handle)))
516       (ignore-errors
517         (cond
518          ;; Internally displayed part.
519          ((mm-annotationp object)
520           (delete-annotation object))
521          ((or (functionp object)
522               (and (listp object)
523                    (eq (car object) 'lambda)))
524           (funcall object))
525          ;; Externally displayed part.
526          ((consp object)
527           (ignore-errors (delete-file (car object)))
528           (ignore-errors (delete-directory (file-name-directory (car object))))
529           (ignore-errors (kill-buffer (cdr object))))
530          ((bufferp object)
531           (when (buffer-live-p object)
532             (kill-buffer object)))))
533       (mm-handle-set-undisplayer handle nil))))
534
535 (defun mm-display-inline (handle)
536   (let* ((type (mm-handle-media-type handle))
537          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
538     (funcall function handle)
539     (goto-char (point-min))))
540
541 (defun mm-assoc-string-match (alist type)
542   (dolist (elem alist)
543     (when (string-match (car elem) type)
544       (return elem))))
545
546 (defun mm-inlinable-p (handle)
547   "Say whether HANDLE can be displayed inline."
548   (let ((alist mm-inline-media-tests)
549         (type (mm-handle-media-type handle))
550         test)
551     (while alist
552       (when (string-match (caar alist) type)
553         (setq test (caddar alist)
554               alist nil)
555         (setq test (funcall test handle)))
556       (pop alist))
557     test))
558
559 (defun mm-automatic-display-p (handle)
560   "Say whether the user wants HANDLE to be displayed automatically."
561   (let ((methods mm-automatic-display)
562         (type (mm-handle-media-type handle))
563         method result)
564     (while (setq method (pop methods))
565       (when (and (not (mm-inline-override-p handle))
566                  (string-match method type)
567                  (mm-inlinable-p handle))
568         (setq result t
569               methods nil)))
570     result))
571
572 (defun mm-inlined-p (handle)
573   "Say whether the user wants HANDLE to be displayed automatically."
574   (let ((methods mm-inlined-types)
575         (type (mm-handle-media-type handle))
576         method result)
577     (while (setq method (pop methods))
578       (when (and (not (mm-inline-override-p handle))
579                  (string-match method type)
580                  (mm-inlinable-p handle))
581         (setq result t
582               methods nil)))
583     result))
584
585 (defun mm-attachment-override-p (handle)
586   "Say whether HANDLE should have attachment behavior overridden."
587   (let ((types mm-attachment-override-types)
588         (type (mm-handle-media-type handle))
589         ty)
590     (catch 'found
591       (while (setq ty (pop types))
592         (when (and (string-match ty type)
593                    (mm-inlinable-p handle))
594           (throw 'found t))))))
595
596 (defun mm-inline-override-p (handle)
597   "Say whether HANDLE should have inline behavior overridden."
598   (let ((types mm-inline-override-types)
599         (type (mm-handle-media-type handle))
600         ty)
601     (catch 'found
602       (while (setq ty (pop types))
603         (when (string-match ty type)
604           (throw 'found t))))))
605
606 (defun mm-automatic-external-display-p (type)
607   "Return the user-defined method for TYPE."
608   (let ((methods mm-automatic-external-display)
609         method result)
610     (while (setq method (pop methods))
611       (when (string-match method type)
612         (setq result t
613               methods nil)))
614     result))
615
616 (defun mm-destroy-part (handle)
617   "Destroy the data structures connected to HANDLE."
618   (when (listp handle)
619     (mm-remove-part handle)
620     (when (buffer-live-p (mm-handle-buffer handle))
621       (kill-buffer (mm-handle-buffer handle)))))
622
623 (defun mm-handle-displayed-p (handle)
624   "Say whether HANDLE is displayed or not."
625   (mm-handle-undisplayer handle))
626
627 ;;;
628 ;;; Functions for outputting parts
629 ;;;
630
631 (defun mm-get-part (handle)
632   "Return the contents of HANDLE as a string."
633   (mm-with-unibyte-buffer
634     (mm-insert-part handle)
635     (buffer-string)))
636
637 (defun mm-insert-part (handle)
638   "Insert the contents of HANDLE in the current buffer."
639   (let ((cur (current-buffer)))
640     (save-excursion
641       (if (member (mm-handle-media-supertype handle) '("text" "message"))
642           (with-temp-buffer
643             (insert-buffer-substring (mm-handle-buffer handle))
644             (mm-decode-content-transfer-encoding
645              (mm-handle-encoding handle)
646              (mm-handle-media-type handle))
647             (let ((temp (current-buffer)))
648               (set-buffer cur)
649               (insert-buffer-substring temp)))
650         (mm-with-unibyte-buffer
651           (insert-buffer-substring (mm-handle-buffer handle))
652           (mm-decode-content-transfer-encoding
653            (mm-handle-encoding handle)
654            (mm-handle-media-type handle))
655           (let ((temp (current-buffer)))
656             (set-buffer cur)
657             (insert-buffer-substring temp)))))))
658
659 (defvar mm-default-directory nil)
660
661 (defun mm-save-part (handle)
662   "Write HANDLE to a file."
663   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
664          (filename (mail-content-type-get
665                     (mm-handle-disposition handle) 'filename))
666          file)
667     (when filename
668       (setq filename (file-name-nondirectory filename)))
669     (setq file
670           (read-file-name "Save MIME part to: "
671                           (expand-file-name
672                            (or filename name "")
673                            (or mm-default-directory default-directory))))
674     (setq mm-default-directory (file-name-directory file))
675     (when (or (not (file-exists-p file))
676               (yes-or-no-p (format "File %s already exists; overwrite? "
677                                    file)))
678       (mm-save-part-to-file handle file))))
679
680 (defun mm-save-part-to-file (handle file)
681   (mm-with-unibyte-buffer
682     (mm-insert-part handle)
683     (let ((coding-system-for-write 'binary)
684           ;; Don't re-compress .gz & al.  Arguably we should make
685           ;; `file-name-handler-alist' nil, but that would chop
686           ;; ange-ftp, which is reasonable to use here.
687           (inhibit-file-name-operation 'write-region)
688           (inhibit-file-name-handlers
689            (cons 'jka-compr-handler inhibit-file-name-handlers)))
690       (write-region (point-min) (point-max) file))))
691
692 (defun mm-pipe-part (handle)
693   "Pipe HANDLE to a process."
694   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
695          (command
696           (read-string "Shell command on MIME part: " mm-last-shell-command)))
697     (mm-with-unibyte-buffer
698       (mm-insert-part handle)
699       (shell-command-on-region (point-min) (point-max) command nil))))
700
701 (defun mm-interactively-view-part (handle)
702   "Display HANDLE using METHOD."
703   (let* ((type (mm-handle-media-type handle))
704          (methods
705           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
706                   (mailcap-mime-info type 'all)))
707          (method (completing-read "Viewer: " methods)))
708     (when (string= method "")
709       (error "No method given"))
710     (if (string-match "^[^% \t]+$" method) 
711         (setq method (concat method " %s")))
712     (mm-display-external (copy-sequence handle) method)))
713
714 (defun mm-preferred-alternative (handles &optional preferred)
715   "Say which of HANDLES are preferred."
716   (let ((prec (if preferred (list preferred)
717                 (mm-preferred-alternative-precedence handles)))
718         p h result type handle)
719     (while (setq p (pop prec))
720       (setq h handles)
721       (while h
722         (setq handle (car h))
723         (setq type (mm-handle-media-type handle))
724         (when (and (equal p type)
725                    (mm-automatic-display-p handle)
726                    (or (stringp (car handle))
727                        (not (mm-handle-disposition handle))
728                        (equal (car (mm-handle-disposition handle))
729                               "inline")))
730           (setq result handle
731                 h nil
732                 prec nil))
733         (pop h)))
734     result))
735
736 (defun mm-preferred-alternative-precedence (handles)
737   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
738   (let ((seq (nreverse (mapcar #'mm-handle-media-type
739                                handles))))
740     (dolist (disc (reverse mm-discouraged-alternatives))
741       (dolist (elem (copy-sequence seq))
742         (when (string-match disc elem)
743           (setq seq (nconc (delete elem seq) (list elem))))))
744     seq))
745
746 (defun mm-get-content-id (id)
747   "Return the handle(s) referred to by ID."
748   (cdr (assoc id mm-content-id-alist)))
749
750 (defun mm-get-image (handle)
751   "Return an image instance based on HANDLE."
752   (let ((type (mm-handle-media-subtype handle))
753         spec)
754     ;; Allow some common translations.
755     (setq type
756           (cond
757            ((equal type "x-pixmap")
758             "xpm")
759            ((equal type "x-xbitmap")
760             "xbm")
761            (t type)))
762     (or (mm-handle-cache handle)
763         (mm-with-unibyte-buffer
764           (mm-insert-part handle)
765           (prog1
766               (setq spec
767                     (ignore-errors
768                       (if (fboundp 'make-glyph)
769                           (cond
770                            ((equal type "xbm")
771                             ;; xbm images require special handling, since
772                             ;; the only way to create glyphs from these
773                             ;; (without a ton of work) is to write them
774                             ;; out to a file, and then create a file
775                             ;; specifier.
776                             (let ((file (make-temp-name
777                                          (expand-file-name "emm.xbm"
778                                                            mm-tmp-directory))))
779                               (unwind-protect
780                                   (progn
781                                     (write-region (point-min) (point-max) file)
782                                     (make-glyph (list (cons 'x file))))
783                                 (ignore-errors
784                                   (delete-file file)))))
785                            (t
786                             (make-glyph
787                              (vector (intern type) :data (buffer-string)))))
788                         (create-image (buffer-string) (intern type) 'data-p))))
789             (mm-handle-set-cache handle spec))))))
790
791 (defun mm-image-fit-p (handle)
792   "Say whether the image in HANDLE will fit the current window."
793   (let ((image (mm-get-image handle)))
794     (if (fboundp 'glyph-width)
795         ;; XEmacs' glyphs can actually tell us about their width, so
796         ;; lets be nice and smart about them.
797         (or mm-inline-large-images
798             (and (< (glyph-width image) (window-pixel-width))
799                  (< (glyph-height image) (window-pixel-height))))
800       (let* ((size (image-size image))
801              (w (car size))
802              (h (cdr size)))
803         (or mm-inline-large-images
804             (and (< h (1- (window-height))) ; Don't include mode line.
805                  (< w (window-width))))))))
806
807 (defun mm-valid-image-format-p (format)
808   "Say whether FORMAT can be displayed natively by Emacs."
809   (cond
810    ;; Handle XEmacs
811    ((fboundp 'valid-image-instantiator-format-p)
812     (valid-image-instantiator-format-p format))
813    ;; Handle Emacs 21
814    ((fboundp 'image-type-available-p)
815     (and (display-graphic-p)
816          (image-type-available-p format)))
817    ;; Nobody else can do images yet.
818    (t
819     nil)))
820
821 (defun mm-valid-and-fit-image-p (format handle)
822   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
823   (and window-system
824        (mm-valid-image-format-p format)
825        (mm-image-fit-p handle)))
826
827 (provide 'mm-decode)
828
829 ;;; mm-decode.el ends here