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