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