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