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