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