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