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