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