78d0cb1492ad8ab274b117ecee2deb4f150dfbae
[elisp/gnus.git-] / 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 'gnus-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 ((flag enable-multibyte-characters)
517           (new-buffer (generate-new-buffer " *mm*")))
518       (goto-char (point-min))
519       (search-forward-regexp "^\n" nil t)
520       (save-restriction
521         (narrow-to-region (point) (point-max))
522         (when flag
523           (set-buffer-multibyte nil))
524         (copy-to-buffer new-buffer (point-min) (point-max))
525         (when flag
526           (set-buffer-multibyte t)))
527       new-buffer)))
528
529 (defun mm-display-parts (handle &optional no-default)
530   (if (stringp (car handle))
531       (mapcar 'mm-display-parts (cdr handle))
532     (if (bufferp (car handle))
533         (save-restriction
534           (narrow-to-region (point) (point))
535           (mm-display-part handle)
536           (goto-char (point-max)))
537       (mapcar 'mm-display-parts handle))))
538
539 (defun mm-display-part (handle &optional no-default)
540   "Display the MIME part represented by HANDLE.
541 Returns nil if the part is removed; inline if displayed inline;
542 external if displayed external."
543   (save-excursion
544     (mailcap-parse-mailcaps)
545     (if (mm-handle-displayed-p handle)
546         (mm-remove-part handle)
547       (let* ((type (mm-handle-media-type handle))
548              (method (mailcap-mime-info type)))
549         (if (and (mm-inlinable-p handle)
550                  (mm-inlined-p handle))
551             (progn
552               (forward-line 1)
553               (mm-display-inline handle)
554               'inline)
555           (when (or method
556                     (not no-default))
557             (if (and (not method)
558                      (equal "text" (car (split-string type))))
559                 (progn
560                   (forward-line 1)
561                   (mm-insert-inline handle (mm-get-part handle))
562                   'inline)
563               (mm-display-external
564                handle (or method 'mailcap-save-binary-file)))))))))
565
566 (defun mm-display-external (handle method)
567   "Display HANDLE using METHOD."
568   (let ((outbuf (current-buffer)))
569     (mm-with-unibyte-buffer
570       (if (functionp method)
571           (let ((cur (current-buffer)))
572             (if (eq method 'mailcap-save-binary-file)
573                 (progn
574                   (set-buffer (generate-new-buffer " *mm*"))
575                   (setq method nil))
576               (mm-insert-part handle)
577               (let ((win (get-buffer-window cur t)))
578                 (when win
579                   (select-window win)))
580               (switch-to-buffer (generate-new-buffer " *mm*")))
581             (buffer-disable-undo)
582             (mm-set-buffer-file-coding-system mm-binary-coding-system)
583             (insert-buffer-substring cur)
584             (goto-char (point-min))
585             (message "Viewing with %s" method)
586             (let ((mm (current-buffer))
587                   (non-viewer (assq 'non-viewer
588                                     (mailcap-mime-info
589                                      (mm-handle-media-type handle) t))))
590               (unwind-protect
591                   (if method
592                       (funcall method)
593                     (mm-save-part handle))
594                 (when (and (not non-viewer)
595                            method)
596                   (mm-handle-set-undisplayer handle mm)))))
597         ;; The function is a string to be executed.
598         (mm-insert-part handle)
599         (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
600                (filename (mail-content-type-get
601                           (mm-handle-disposition handle) 'filename))
602                (mime-info (mailcap-mime-info
603                            (mm-handle-media-type handle) t))
604                (needsterm (or (assoc "needsterm" mime-info)
605                               (assoc "needsterminal" mime-info)))
606                (copiousoutput (assoc "copiousoutput" mime-info))
607                file buffer)
608           ;; We create a private sub-directory where we store our files.
609           (make-directory dir)
610           (set-file-modes dir 448)
611           (if filename
612               (setq file (expand-file-name (file-name-nondirectory filename)
613                                            dir))
614             (setq file (make-temp-name (expand-file-name "mm." dir))))
615           (let ((coding-system-for-write mm-binary-coding-system))
616             (write-region (point-min) (point-max) file nil 'nomesg))
617           (message "Viewing with %s" method)
618           (cond (needsterm
619                  (unwind-protect
620                      (start-process "*display*" nil
621                                     "xterm"
622                                     "-e" shell-file-name
623                                     shell-command-switch
624                                     (mm-mailcap-command
625                                      method file (mm-handle-type handle)))
626                    (mm-handle-set-external-undisplayer handle (cons file buffer)))
627                  (message "Displaying %s..." (format method file))
628                  'external)
629                 (copiousoutput
630                  (with-current-buffer outbuf
631                    (forward-line 1)
632                    (mm-insert-inline
633                     handle
634                     (unwind-protect
635                         (progn
636                           (call-process shell-file-name nil
637                                         (setq buffer
638                                               (generate-new-buffer " *mm*"))
639                                         nil
640                                         shell-command-switch
641                                         (mm-mailcap-command
642                                          method file (mm-handle-type handle)))
643                           (if (buffer-live-p buffer)
644                               (save-excursion
645                                 (set-buffer buffer)
646                                 (buffer-string))))
647                       (progn
648                         (ignore-errors (delete-file file))
649                         (ignore-errors (delete-directory
650                                         (file-name-directory file)))
651                         (ignore-errors (kill-buffer buffer))))))
652                  'inline)
653                 (t
654                  (unwind-protect
655                      (start-process "*display*"
656                                     (setq buffer
657                                           (generate-new-buffer " *mm*"))
658                                     shell-file-name
659                                     shell-command-switch
660                                     (mm-mailcap-command
661                                      method file (mm-handle-type handle)))
662                    (mm-handle-set-external-undisplayer handle (cons file buffer)))
663                  (message "Displaying %s..." (format method file))
664                  'external)))))))
665
666 (defun mm-mailcap-command (method file type-list)
667   (let ((ctl (cdr type-list))
668         (beg 0)
669         (uses-stdin t)
670         out sub total)
671     (while (string-match "%{\\([^}]+\\)}\\|%s\\|%t\\|%%" method beg)
672       (push (substring method beg (match-beginning 0)) out)
673       (setq beg (match-end 0)
674             total (match-string 0 method)
675             sub (match-string 1 method))
676       (cond
677        ((string= total "%%")
678         (push "%" out))
679        ((string= total "%s")
680         (setq uses-stdin nil)
681         (push (mm-quote-arg file) out))
682        ((string= total "%t")
683         (push (mm-quote-arg (car type-list)) out))
684        (t
685         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
686     (push (substring method beg (length method)) out)
687     (if uses-stdin
688         (progn
689           (push "<" out)
690           (push (mm-quote-arg file) out)))
691     (mapconcat 'identity (nreverse out) "")))
692
693 (defun mm-remove-parts (handles)
694   "Remove the displayed MIME parts represented by HANDLES."
695   (if (and (listp handles)
696            (bufferp (car handles)))
697       (mm-remove-part handles)
698     (let (handle)
699       (while (setq handle (pop handles))
700         (cond
701          ((stringp handle)
702           (when (buffer-live-p (get-text-property 0 'buffer handle))
703             (kill-buffer (get-text-property 0 'buffer handle))))
704          ((and (listp handle)
705                (stringp (car handle)))
706           (mm-remove-parts (cdr handle)))
707          (t
708           (mm-remove-part handle)))))))
709
710 (defun mm-destroy-parts (handles)
711   "Remove the displayed MIME parts represented by HANDLES."
712   (if (and (listp handles)
713            (bufferp (car handles)))
714       (mm-destroy-part handles)
715     (let (handle)
716       (while (setq handle (pop handles))
717         (cond
718          ((stringp handle)
719           (when (buffer-live-p (get-text-property 0 'buffer handle))
720             (kill-buffer (get-text-property 0 'buffer handle))))
721          ((and (listp handle)
722                (stringp (car handle)))
723           (mm-destroy-parts handle))
724          (t
725           (mm-destroy-part handle)))))))
726
727 (defun mm-remove-part (handle)
728   "Remove the displayed MIME part represented by HANDLE."
729   (when (listp handle)
730     (let ((object (mm-handle-undisplayer handle)))
731       (ignore-errors
732         (cond
733          ;; Internally displayed part.
734          ((mm-annotationp object)
735           (delete-annotation object))
736          ((or (functionp object)
737               (and (listp object)
738                    (eq (car object) 'lambda)))
739           (funcall object))
740          ;; Externally displayed part.
741          ((consp object)
742           (ignore-errors (delete-file (car object)))
743           (ignore-errors (delete-directory (file-name-directory (car object))))
744           (ignore-errors (kill-buffer (cdr object))))
745          ((bufferp object)
746           (when (buffer-live-p object)
747             (kill-buffer object)))))
748       (mm-handle-set-undisplayer handle nil))))
749
750 (defun mm-display-inline (handle)
751   (let* ((type (mm-handle-media-type handle))
752          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
753     (funcall function handle)
754     (goto-char (point-min))))
755
756 (defun mm-assoc-string-match (alist type)
757   (dolist (elem alist)
758     (when (string-match (car elem) type)
759       (return elem))))
760
761 (defun mm-automatic-display-p (handle)
762   "Say whether the user wants HANDLE to be displayed automatically."
763   (let ((methods mm-automatic-display)
764         (type (mm-handle-media-type handle))
765         method result)
766     (while (setq method (pop methods))
767       (when (and (not (mm-inline-override-p handle))
768                  (string-match method type))
769         (setq result t
770               methods nil)))
771     result))
772
773 (defun mm-inlinable-p (handle)
774   "Say whether HANDLE can be displayed inline."
775   (let ((alist mm-inline-media-tests)
776         (type (mm-handle-media-type handle))
777         test)
778     (while alist
779       (when (string-match (caar alist) type)
780         (setq test (caddar alist)
781               alist nil)
782         (setq test (funcall test handle)))
783       (pop alist))
784     test))
785
786 (defun mm-inlined-p (handle)
787   "Say whether the user wants HANDLE to be displayed inline."
788   (let ((methods mm-inlined-types)
789         (type (mm-handle-media-type handle))
790         method result)
791     (while (setq method (pop methods))
792       (when (and (not (mm-inline-override-p handle))
793                  (string-match method type))
794         (setq result t
795               methods nil)))
796     result))
797
798 (defun mm-attachment-override-p (handle)
799   "Say whether HANDLE should have attachment behavior overridden."
800   (let ((types mm-attachment-override-types)
801         (type (mm-handle-media-type handle))
802         ty)
803     (catch 'found
804       (while (setq ty (pop types))
805         (when (and (string-match ty type)
806                    (mm-inlinable-p handle))
807           (throw 'found t))))))
808
809 (defun mm-inline-override-p (handle)
810   "Say whether HANDLE should have inline behavior overridden."
811   (let ((types mm-inline-override-types)
812         (type (mm-handle-media-type handle))
813         ty)
814     (catch 'found
815       (while (setq ty (pop types))
816         (when (string-match ty type)
817           (throw 'found t))))))
818
819 (defun mm-automatic-external-display-p (type)
820   "Return the user-defined method for TYPE."
821   (let ((methods mm-automatic-external-display)
822         method result)
823     (while (setq method (pop methods))
824       (when (string-match method type)
825         (setq result t
826               methods nil)))
827     result))
828
829 (defun mm-destroy-part (handle)
830   "Destroy the data structures connected to HANDLE."
831   (when (listp handle)
832     (mm-remove-part handle)
833     (when (buffer-live-p (mm-handle-buffer handle))
834       (kill-buffer (mm-handle-buffer handle)))))
835
836 (defun mm-handle-displayed-p (handle)
837   "Say whether HANDLE is displayed or not."
838   (mm-handle-undisplayer handle))
839
840 ;;;
841 ;;; Functions for outputting parts
842 ;;;
843
844 (defun mm-get-part (handle)
845   "Return the contents of HANDLE as a string."
846   (mm-with-unibyte-buffer
847     (insert (with-current-buffer (mm-handle-buffer handle)
848               (mm-with-unibyte-current-buffer-mule4
849                 (buffer-string))))
850     (mm-decode-content-transfer-encoding
851      (mm-handle-encoding handle)
852      (mm-handle-media-type handle))
853     (buffer-string)))
854
855 (defun mm-insert-part (handle)
856   "Insert the contents of HANDLE in the current buffer."
857   (let ((cur (current-buffer)))
858     (save-excursion
859       (if (member (mm-handle-media-supertype handle) '("text" "message"))
860           (with-temp-buffer
861             (insert-buffer-substring (mm-handle-buffer handle))
862             (mm-decode-content-transfer-encoding
863              (mm-handle-encoding handle)
864              (mm-handle-media-type handle))
865             (let ((temp (current-buffer)))
866               (set-buffer cur)
867               (insert-buffer-substring temp)))
868         (mm-with-unibyte-buffer
869           (insert-buffer-substring (mm-handle-buffer handle))
870           (mm-decode-content-transfer-encoding
871            (mm-handle-encoding handle)
872            (mm-handle-media-type handle))
873           (let ((temp (current-buffer)))
874             (set-buffer cur)
875             (insert-buffer-substring temp)))))))
876
877 (defun mm-file-name-delete-whitespace (file-name)
878   "Remove all whitespace characters from FILE-NAME."
879   (while (string-match "\\s-+" file-name)
880     (setq file-name (replace-match "" t t file-name)))
881   file-name)
882
883 (defun mm-file-name-trim-whitespace (file-name)
884   "Remove leading and trailing whitespace characters from FILE-NAME."
885   (when (string-match "\\`\\s-+" file-name)
886     (setq file-name (substring file-name (match-end 0))))
887   (when (string-match "\\s-+\\'" file-name)
888     (setq file-name (substring file-name 0 (match-beginning 0))))
889   file-name)
890
891 (defun mm-file-name-collapse-whitespace (file-name)
892   "Collapse multiple whitespace characters in FILE-NAME."
893   (while (string-match "\\s-\\s-+" file-name)
894     (setq file-name (replace-match " " t t file-name)))
895   file-name)
896
897 (defun mm-file-name-replace-whitespace (file-name)
898   "Replace whitespace characters in FILE-NAME with underscores.
899 Set `mm-file-name-replace-whitespace' to any other string if you do not
900 like underscores."
901   (let ((s (or mm-file-name-replace-whitespace "_")))
902     (while (string-match "\\s-" file-name)
903       (setq file-name (replace-match s t t file-name))))
904   file-name)
905
906 (defun mm-save-part (handle)
907   "Write HANDLE to a file."
908   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
909          (filename (mail-content-type-get
910                     (mm-handle-disposition handle) 'filename))
911          file)
912     (when filename
913       (setq filename (gnus-map-function mm-file-name-rewrite-functions
914                                         (file-name-nondirectory filename))))
915     (setq file
916           (read-file-name "Save MIME part to: "
917                           (expand-file-name
918                            (or filename name "")
919                            (or mm-default-directory default-directory))))
920     (setq mm-default-directory (file-name-directory file))
921     (and (or (not (file-exists-p file))
922              (yes-or-no-p (format "File %s already exists; overwrite? "
923                                   file)))
924          (progn
925            (mm-save-part-to-file handle file)
926            file))))
927
928 (defun mm-save-part-to-file (handle file)
929   (mm-with-unibyte-buffer
930     (mm-insert-part handle)
931     (let ((coding-system-for-write 'binary)
932           ;; Don't re-compress .gz & al.  Arguably we should make
933           ;; `file-name-handler-alist' nil, but that would chop
934           ;; ange-ftp, which is reasonable to use here.
935           (inhibit-file-name-operation 'write-region)
936           (inhibit-file-name-handlers
937            (cons 'jka-compr-handler inhibit-file-name-handlers)))
938       (write-region (point-min) (point-max) file))))
939
940 (defun mm-pipe-part (handle)
941   "Pipe HANDLE to a process."
942   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
943          (command
944           (read-string "Shell command on MIME part: " mm-last-shell-command)))
945     (mm-with-unibyte-buffer
946       (mm-insert-part handle)
947       (let ((coding-system-for-write 'binary))
948         (shell-command-on-region (point-min) (point-max) command nil)))))
949
950 (defun mm-interactively-view-part (handle)
951   "Display HANDLE using METHOD."
952   (let* ((type (mm-handle-media-type handle))
953          (methods
954           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
955                   (mailcap-mime-info type 'all)))
956          (method (let ((minibuffer-local-completion-map
957                         mm-viewer-completion-map))
958                    (completing-read "Viewer: " methods))))
959     (when (string= method "")
960       (error "No method given"))
961     (if (string-match "^[^% \t]+$" method)
962         (setq method (concat method " %s")))
963     (mm-display-external handle method)))
964
965 (defun mm-preferred-alternative (handles &optional preferred)
966   "Say which of HANDLES are preferred."
967   (let ((prec (if preferred (list preferred)
968                 (mm-preferred-alternative-precedence handles)))
969         p h result type handle)
970     (while (setq p (pop prec))
971       (setq h handles)
972       (while h
973         (setq handle (car h))
974         (setq type (mm-handle-media-type handle))
975         (when (and (equal p type)
976                    (mm-automatic-display-p handle)
977                    (or (stringp (car handle))
978                        (not (mm-handle-disposition handle))
979                        (equal (car (mm-handle-disposition handle))
980                               "inline")))
981           (setq result handle
982                 h nil
983                 prec nil))
984         (pop h)))
985     result))
986
987 (defun mm-preferred-alternative-precedence (handles)
988   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
989   (let ((seq (nreverse (mapcar #'mm-handle-media-type
990                                handles))))
991     (dolist (disc (reverse mm-discouraged-alternatives))
992       (dolist (elem (copy-sequence seq))
993         (when (string-match disc elem)
994           (setq seq (nconc (delete elem seq) (list elem))))))
995     seq))
996
997 (defun mm-get-content-id (id)
998   "Return the handle(s) referred to by ID."
999   (cdr (assoc id mm-content-id-alist)))
1000
1001 (defun mm-get-image (handle)
1002   "Return an image instance based on HANDLE."
1003   (let ((type (mm-handle-media-subtype handle))
1004         spec)
1005     ;; Allow some common translations.
1006     (setq type
1007           (cond
1008            ((equal type "x-pixmap")
1009             "xpm")
1010            ((equal type "x-xbitmap")
1011             "xbm")
1012            ((equal type "x-portable-bitmap")
1013             "pbm")
1014            (t type)))
1015     (or (mm-handle-cache handle)
1016         (mm-with-unibyte-buffer
1017           (mm-insert-part handle)
1018           (prog1
1019               (setq spec
1020                     (ignore-errors
1021                      ;; Avoid testing `make-glyph' since W3 may define
1022                      ;; a bogus version of it.
1023                       (if (fboundp 'create-image)
1024                           (create-image (buffer-string) (intern type) 'data-p)
1025                         (cond
1026                          ((equal type "xbm")
1027                           ;; xbm images require special handling, since
1028                           ;; the only way to create glyphs from these
1029                           ;; (without a ton of work) is to write them
1030                           ;; out to a file, and then create a file
1031                           ;; specifier.
1032                           (let ((file (make-temp-name
1033                                        (expand-file-name "emm.xbm"
1034                                                          mm-tmp-directory))))
1035                             (unwind-protect
1036                                 (progn
1037                                   (write-region (point-min) (point-max) file)
1038                                   (make-glyph (list (cons 'x file))))
1039                               (ignore-errors
1040                                (delete-file file)))))
1041                          (t
1042                           (make-glyph
1043                            (vector (intern type) :data (buffer-string))))))))
1044             (mm-handle-set-cache handle spec))))))
1045
1046 (defun mm-image-fit-p (handle)
1047   "Say whether the image in HANDLE will fit the current window."
1048   (let ((image (mm-get-image handle)))
1049     (if (fboundp 'glyph-width)
1050         ;; XEmacs' glyphs can actually tell us about their width, so
1051         ;; lets be nice and smart about them.
1052         (or mm-inline-large-images
1053             (and (< (glyph-width image) (window-pixel-width))
1054                  (< (glyph-height image) (window-pixel-height))))
1055       (let* ((size (image-size image))
1056              (w (car size))
1057              (h (cdr size)))
1058         (or mm-inline-large-images
1059             (and (< h (1- (window-height))) ; Don't include mode line.
1060                  (< w (window-width))))))))
1061
1062 (defun mm-valid-image-format-p (format)
1063   "Say whether FORMAT can be displayed natively by Emacs."
1064   (cond
1065    ;; Handle XEmacs
1066    ((fboundp 'valid-image-instantiator-format-p)
1067     (valid-image-instantiator-format-p format))
1068    ;; Handle Emacs 21
1069    ((fboundp 'image-type-available-p)
1070     (and (display-graphic-p)
1071          (image-type-available-p format)))
1072    ;; Nobody else can do images yet.
1073    (t
1074     nil)))
1075
1076 (defun mm-valid-and-fit-image-p (format handle)
1077   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
1078   (and (mm-valid-image-format-p format)
1079        (mm-image-fit-p handle)))
1080
1081 (defun mm-find-part-by-type (handles type &optional notp recursive)
1082   "Search in HANDLES for part with TYPE.
1083 If NOTP, returns first non-matching part.
1084 If RECURSIVE, search recursively."
1085   (let (handle)
1086     (while handles
1087       (if (and recursive (stringp (caar handles)))
1088           (if (setq handle (mm-find-part-by-type (cdar handles) type
1089                                                  notp recursive))
1090               (setq handles nil))
1091         (if (if notp
1092                 (not (equal (mm-handle-media-type (car handles)) type))
1093               (equal (mm-handle-media-type (car handles)) type))
1094             (setq handle (car handles)
1095                   handles nil)))
1096       (setq handles (cdr handles)))
1097     handle))
1098
1099 (defun mm-find-raw-part-by-type (ctl type &optional notp)
1100   (goto-char (point-min))
1101   (let* ((boundary (concat "--" (mm-handle-multipart-ctl-parameter ctl
1102                                                                    'boundary)))
1103          (close-delimiter (concat "^" (regexp-quote boundary) "--[ \t]*$"))
1104          start
1105          (end (save-excursion
1106                 (goto-char (point-max))
1107                 (if (re-search-backward close-delimiter nil t)
1108                     (match-beginning 0)
1109                   (point-max))))
1110          result)
1111     (setq boundary (concat "^" (regexp-quote boundary) "[ \t]*$"))
1112     (while (and (not result)
1113                 (re-search-forward boundary end t))
1114       (goto-char (match-beginning 0))
1115       (when start
1116         (save-excursion
1117           (save-restriction
1118             (narrow-to-region start (1- (point)))
1119             (when (let ((ctl (ignore-errors
1120                                (mail-header-parse-content-type
1121                                 (mail-fetch-field "content-type")))))
1122                     (if notp
1123                         (not (equal (car ctl) type))
1124                       (equal (car ctl) type)))
1125               (setq result (buffer-substring (point-min) (point-max)))))))
1126       (forward-line 1)
1127       (setq start (point)))
1128     (when (and (not result) start)
1129       (save-excursion
1130         (save-restriction
1131           (narrow-to-region start end)
1132           (when (let ((ctl (ignore-errors
1133                              (mail-header-parse-content-type
1134                               (mail-fetch-field "content-type")))))
1135                   (if notp
1136                       (not (equal (car ctl) type))
1137                     (equal (car ctl) type)))
1138             (setq result (buffer-substring (point-min) (point-max)))))))
1139     result))
1140
1141 (defvar mm-security-handle nil)
1142
1143 (defsubst mm-set-handle-multipart-parameter (handle parameter value)
1144   ;; HANDLE could be a CTL.
1145   (if handle
1146       (put-text-property 0 (length (car handle)) parameter value
1147                          (car handle))))
1148
1149 (defun mm-possibly-verify-or-decrypt (parts ctl)
1150   (let ((subtype (cadr (split-string (car ctl) "/")))
1151         (mm-security-handle ctl) ;; (car CTL) is the type.
1152         protocol func functest)
1153     (cond
1154      ((equal subtype "signed")
1155       (unless (and (setq protocol
1156                          (mm-handle-multipart-ctl-parameter ctl 'protocol))
1157                    (not (equal protocol "multipart/mixed")))
1158         ;; The message is broken or draft-ietf-openpgp-multsig-01.
1159         (let ((protocols mm-verify-function-alist))
1160           (while protocols
1161             (if (and (or (not (setq functest (nth 3 (car protocols))))
1162                          (funcall functest parts ctl))
1163                      (mm-find-part-by-type parts (caar protocols) nil t))
1164                 (setq protocol (caar protocols)
1165                       protocols nil)
1166               (setq protocols (cdr protocols))))))
1167       (setq func (nth 1 (assoc protocol mm-verify-function-alist)))
1168       (if (cond
1169            ((eq mm-verify-option 'never) nil)
1170            ((eq mm-verify-option 'always) t)
1171            ((eq mm-verify-option 'known)
1172             (and func
1173                  (or (not (setq functest
1174                                 (nth 3 (assoc protocol
1175                                               mm-verify-function-alist))))
1176                      (funcall functest parts ctl))))
1177            (t (y-or-n-p
1178                (format "Verify signed (%s) part? "
1179                        (or (nth 2 (assoc protocol mm-verify-function-alist))
1180                            (format "protocol=%s" protocol))))))
1181           (save-excursion
1182             (if func
1183                 (funcall func parts ctl)
1184               (mm-set-handle-multipart-parameter
1185                mm-security-handle 'gnus-details
1186                (format "Unknown sign protocol (%s)" protocol))))))
1187      ((equal subtype "encrypted")
1188       (unless (setq protocol
1189                     (mm-handle-multipart-ctl-parameter ctl 'protocol))
1190         ;; The message is broken.
1191         (let ((parts parts))
1192           (while parts
1193             (if (assoc (mm-handle-media-type (car parts))
1194                        mm-decrypt-function-alist)
1195                 (setq protocol (mm-handle-media-type (car parts))
1196                       parts nil)
1197               (setq parts (cdr parts))))))
1198       (setq func (nth 1 (assoc protocol mm-decrypt-function-alist)))
1199       (if (cond
1200            ((eq mm-decrypt-option 'never) nil)
1201            ((eq mm-decrypt-option 'always) t)
1202            ((eq mm-decrypt-option 'known)
1203             (and func
1204                  (or (not (setq functest
1205                                 (nth 3 (assoc protocol
1206                                               mm-decrypt-function-alist))))
1207                      (funcall functest parts ctl))))
1208            (t (y-or-n-p
1209                (format "Decrypt (%s) part? "
1210                        (or (nth 2 (assoc protocol mm-decrypt-function-alist))
1211                            (format "protocol=%s" protocol))))))
1212           (save-excursion
1213             (if func
1214                 (setq parts (funcall func parts ctl))
1215               (mm-set-handle-multipart-parameter
1216                mm-security-handle 'gnus-details
1217                (format "Unknown encrypt protocol (%s)" protocol))))))
1218      (t nil))
1219     parts))
1220
1221 (defun mm-multiple-handles (handles)
1222    (and (listp (car handles)) 
1223         (> (length handles) 1)))
1224
1225 (defun mm-merge-handles (handles1 handles2) 
1226   (append
1227    (if (listp (car handles1)) 
1228        handles1
1229      (list handles1))
1230    (if (listp (car handles2))
1231        handles2
1232      (list handles2))))
1233
1234 (provide 'mm-decode)
1235
1236 ;;; mm-decode.el ends here