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