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