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