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