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