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