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