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