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