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