(mm-enable-external): New variable.
[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 'executable-find "executable")
36   (autoload 'mm-inline-partial "mm-partial")
37   (autoload 'mm-inline-external-body "mm-extern")
38   (autoload 'mm-insert-inline "mm-view"))
39
40 (add-hook 'gnus-exit-gnus-hook 'mm-destroy-postponed-undisplay-list)
41
42 (defgroup mime-display ()
43   "Display of MIME in mail and news articles."
44   :link '(custom-manual "(emacs-mime)Customization")
45   :version "21.1"
46   :group 'mail
47   :group 'news
48   :group 'multimedia)
49
50 (defgroup mime-security ()
51   "MIME security in mail and news articles."
52   :link '(custom-manual "(emacs-mime)Customization")
53   :group 'mail
54   :group 'news
55   :group 'multimedia)
56
57 ;;; Convenience macros.
58
59 (defmacro mm-handle-buffer (handle)
60   `(nth 0 ,handle))
61 (defmacro mm-handle-type (handle)
62   `(nth 1 ,handle))
63 (defsubst mm-handle-media-type (handle)
64   (if (stringp (car handle))
65       (car handle)
66     (car (mm-handle-type handle))))
67 (defsubst mm-handle-media-supertype (handle)
68   (car (split-string (mm-handle-media-type handle) "/")))
69 (defsubst mm-handle-media-subtype (handle)
70   (cadr (split-string (mm-handle-media-type handle) "/")))
71 (defmacro mm-handle-encoding (handle)
72   `(nth 2 ,handle))
73 (defmacro mm-handle-undisplayer (handle)
74   `(nth 3 ,handle))
75 (defmacro mm-handle-set-undisplayer (handle function)
76   `(setcar (nthcdr 3 ,handle) ,function))
77 (defmacro mm-handle-disposition (handle)
78   `(nth 4 ,handle))
79 (defmacro mm-handle-description (handle)
80   `(nth 5 ,handle))
81 (defmacro mm-handle-cache (handle)
82   `(nth 6 ,handle))
83 (defmacro mm-handle-set-cache (handle contents)
84   `(setcar (nthcdr 6 ,handle) ,contents))
85 (defmacro mm-handle-id (handle)
86   `(nth 7 ,handle))
87 (defmacro mm-handle-multipart-original-buffer (handle)
88   `(get-text-property 0 'buffer (car ,handle)))
89 (defmacro mm-handle-multipart-from (handle)
90   `(get-text-property 0 'from (car ,handle)))
91 (defmacro mm-handle-multipart-ctl-parameter (handle parameter)
92   `(get-text-property 0 ,parameter (car ,handle)))
93
94 (defmacro mm-make-handle (&optional buffer type encoding undisplayer
95                                     disposition description cache
96                                     id)
97   `(list ,buffer ,type ,encoding ,undisplayer
98          ,disposition ,description ,cache ,id))
99
100 (defcustom mm-text-html-renderer
101   (cond ((locate-library "w3") 'w3)
102         ((locate-library "w3m") 'w3m)
103         ((executable-find "w3m") '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       (when cte
526         (setq cte (mail-header-strip cte)))
527       (if (or (not ctl)
528               (not (string-match "/" (car ctl))))
529           (mm-dissect-singlepart
530            (list mm-dissect-default-type)
531            (and cte (intern (downcase (mail-header-remove-whitespace
532                                        (mail-header-remove-comments
533                                         cte)))))
534            no-strict-mime
535            (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
536            description)
537         (setq type (split-string (car ctl) "/"))
538         (setq subtype (cadr type)
539               type (pop type))
540         (setq
541          result
542          (cond
543           ((equal type "multipart")
544            (let ((mm-dissect-default-type (if (equal subtype "digest")
545                                               "message/rfc822"
546                                             "text/plain"))
547                  (start (cdr (assq 'start (cdr ctl)))))
548              (add-text-properties 0 (length (car ctl))
549                                   (mm-alist-to-plist (cdr ctl)) (car ctl))
550
551              ;; what really needs to be done here is a way to link a
552              ;; MIME handle back to it's parent MIME handle (in a multilevel
553              ;; MIME article).  That would probably require changing
554              ;; the mm-handle API so we simply store the multipart buffert
555              ;; name as a text property of the "multipart/whatever" string.
556              (add-text-properties 0 (length (car ctl))
557                                   (list 'buffer (mm-copy-to-buffer)
558                                         'from from
559                                         'start start)
560                                   (car ctl))
561              (cons (car ctl) (mm-dissect-multipart ctl))))
562           (t
563            (mm-possibly-verify-or-decrypt
564             (mm-dissect-singlepart
565              ctl
566              (and cte (intern (downcase (mail-header-remove-whitespace
567                                          (mail-header-remove-comments
568                                           cte)))))
569              no-strict-mime
570              (and cd (ignore-errors
571                        (mail-header-parse-content-disposition cd)))
572              description id)
573             ctl))))
574         (when id
575           (when (string-match " *<\\(.*\\)> *" id)
576             (setq id (match-string 1 id)))
577           (push (cons id result) mm-content-id-alist))
578         result))))
579
580 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
581   (when (or force
582             (if (equal "text/plain" (car ctl))
583                 (assoc 'format ctl)
584               t))
585     (mm-make-handle
586      (mm-copy-to-buffer) ctl cte nil cdl description nil id)))
587
588 (defun mm-dissect-multipart (ctl)
589   (goto-char (point-min))
590   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
591          (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
592          start parts
593          (end (save-excursion
594                 (goto-char (point-max))
595                 (if (re-search-backward close-delimiter nil t)
596                     (match-beginning 0)
597                   (point-max)))))
598     (setq boundary (concat (regexp-quote boundary) "[ \t]*$"))
599     (while (and (< (point) end) (re-search-forward boundary end t))
600       (goto-char (match-beginning 0))
601       (when start
602         (save-excursion
603           (save-restriction
604             (narrow-to-region start (point))
605             (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
606       (end-of-line 2)
607       (or (looking-at boundary)
608           (forward-line 1))
609       (setq start (point)))
610     (when (and start (< start end))
611       (save-excursion
612         (save-restriction
613           (narrow-to-region start end)
614           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
615     (mm-possibly-verify-or-decrypt (nreverse parts) ctl)))
616
617 (defun mm-copy-to-buffer ()
618   "Copy the contents of the current buffer to a fresh buffer."
619   (save-excursion
620     (let ((obuf (current-buffer))
621           beg)
622       (goto-char (point-min))
623       (search-forward-regexp "^\n" nil t)
624       (setq beg (point))
625       (set-buffer (generate-new-buffer " *mm*"))
626       (insert-buffer-substring obuf beg)
627       (current-buffer))))
628
629 (defun mm-display-parts (handle &optional no-default)
630   (if (stringp (car handle))
631       (mapcar 'mm-display-parts (cdr handle))
632     (if (bufferp (car handle))
633         (save-restriction
634           (narrow-to-region (point) (point))
635           (mm-display-part handle)
636           (goto-char (point-max)))
637       (mapcar 'mm-display-parts handle))))
638
639 (defun mm-display-part (handle &optional no-default)
640   "Display the MIME part represented by HANDLE.
641 Returns nil if the part is removed; inline if displayed inline;
642 external if displayed external."
643   (save-excursion
644     (mailcap-parse-mailcaps)
645     (if (mm-handle-displayed-p handle)
646         (mm-remove-part handle)
647       (let* ((type (mm-handle-media-type handle))
648              (method (mailcap-mime-info type))
649              (filename (or (mail-content-type-get
650                             (mm-handle-disposition handle) 'filename)
651                            (mail-content-type-get
652                             (mm-handle-type handle) 'name)
653                            "<file>"))
654              (external mm-enable-external))
655         (if (and (mm-inlinable-p handle)
656                  (mm-inlined-p handle))
657             (progn
658               (forward-line 1)
659               (mm-display-inline handle)
660               'inline)
661           (when (or method
662                     (not no-default))
663             (if (and (not method)
664                      (equal "text" (car (split-string type))))
665                 (progn
666                   (forward-line 1)
667                   (mm-insert-inline handle (mm-get-part handle))
668                   'inline)
669               (if (and method ;; If nil, we always use "save".
670                        (stringp method) ;; 'mailcap-save-binary-file
671                        (or (eq mm-enable-external t)
672                            (and (eq mm-enable-external 'ask)
673                                 (y-or-n-p
674                                  (concat
675                                   "Display part (" type
676                                   ") using external program"
677                                   ;; Can non-string method ever happen?
678                                   (if (stringp method)
679                                       (concat
680                                        " \"" (format method filename) "\"")
681                                     "")
682                                   "? ")))))
683                   (setq external t)
684                 (setq external nil))
685               (if external
686                   (mm-display-external
687                    handle (or method 'mailcap-save-binary-file))
688                 (mm-display-external
689                  handle 'mailcap-save-binary-file)))))))))
690
691 (defun mm-display-external (handle method)
692   "Display HANDLE using METHOD."
693   (let ((outbuf (current-buffer)))
694     (mm-with-unibyte-buffer
695       (if (functionp method)
696           (let ((cur (current-buffer)))
697             (if (eq method 'mailcap-save-binary-file)
698                 (progn
699                   (set-buffer (generate-new-buffer " *mm*"))
700                   (setq method nil))
701               (mm-insert-part handle)
702               (let ((win (get-buffer-window cur t)))
703                 (when win
704                   (select-window win)))
705               (switch-to-buffer (generate-new-buffer " *mm*")))
706             (buffer-disable-undo)
707             (mm-set-buffer-file-coding-system mm-binary-coding-system)
708             (insert-buffer-substring cur)
709             (goto-char (point-min))
710             (when method
711               (message "Viewing with %s" method))
712             (let ((mm (current-buffer))
713                   (non-viewer (assq 'non-viewer
714                                     (mailcap-mime-info
715                                      (mm-handle-media-type handle) t))))
716               (unwind-protect
717                   (if method
718                       (funcall method)
719                     (mm-save-part handle))
720                 (when (and (not non-viewer)
721                            method)
722                   (mm-handle-set-undisplayer handle mm)))))
723         ;; The function is a string to be executed.
724         (mm-insert-part handle)
725         (let* ((dir (mm-make-temp-file
726                      (expand-file-name "emm." mm-tmp-directory) 'dir))
727                (filename (or
728                           (mail-content-type-get
729                            (mm-handle-disposition handle) 'filename)
730                           (mail-content-type-get
731                            (mm-handle-type handle) 'name)))
732                (mime-info (mailcap-mime-info
733                            (mm-handle-media-type handle) t))
734                (needsterm (or (assoc "needsterm" mime-info)
735                               (assoc "needsterminal" mime-info)))
736                (copiousoutput (assoc "copiousoutput" mime-info))
737                file buffer)
738           ;; We create a private sub-directory where we store our files.
739           (set-file-modes dir 448)
740           (if filename
741               (setq file (expand-file-name
742                           (gnus-map-function mm-file-name-rewrite-functions
743                                              (file-name-nondirectory filename))
744                           dir))
745             (setq file (mm-make-temp-file (expand-file-name "mm." dir))))
746           (let ((coding-system-for-write mm-binary-coding-system))
747             (write-region (point-min) (point-max) file nil 'nomesg))
748           (message "Viewing with %s" method)
749           (cond
750            (needsterm
751             (let ((command (mm-mailcap-command
752                             method file (mm-handle-type handle))))
753               (unwind-protect
754                   (if window-system
755                       (start-process "*display*" nil
756                                      mm-external-terminal-program
757                                      "-e" shell-file-name
758                                      shell-command-switch command)
759                     (require 'term)
760                     (require 'gnus-win)
761                     (set-buffer
762                      (setq buffer
763                            (make-term "display"
764                                       shell-file-name
765                                       nil
766                                       shell-command-switch command)))
767                     (term-mode)
768                     (term-char-mode)
769                     (set-process-sentinel
770                      (get-buffer-process buffer)
771                      `(lambda (process state)
772                         (if (eq 'exit (process-status process))
773                             (gnus-configure-windows
774                              ',gnus-current-window-configuration))))
775                     (gnus-configure-windows 'display-term))
776                 (mm-handle-set-external-undisplayer handle (cons file buffer)))
777               (message "Displaying %s..." command))
778             'external)
779            (copiousoutput
780             (with-current-buffer outbuf
781               (forward-line 1)
782               (mm-insert-inline
783                handle
784                (unwind-protect
785                    (progn
786                      (call-process shell-file-name nil
787                                    (setq buffer
788                                          (generate-new-buffer " *mm*"))
789                                    nil
790                                    shell-command-switch
791                                    (mm-mailcap-command
792                                     method file (mm-handle-type handle)))
793                      (if (buffer-live-p buffer)
794                          (save-excursion
795                            (set-buffer buffer)
796                            (buffer-string))))
797                  (progn
798                    (ignore-errors (delete-file file))
799                    (ignore-errors (delete-directory
800                                    (file-name-directory file)))
801                    (ignore-errors (kill-buffer buffer))))))
802             'inline)
803            (t
804             (let ((command (mm-mailcap-command
805                             method file (mm-handle-type handle))))
806               (unwind-protect
807                   (start-process "*display*"
808                                  (setq buffer
809                                        (generate-new-buffer " *mm*"))
810                                  shell-file-name
811                                  shell-command-switch command)
812                 (mm-handle-set-external-undisplayer
813                  handle (cons file buffer)))
814               (message "Displaying %s..." command))
815             'external)))))))
816
817 (defun mm-mailcap-command (method file type-list)
818   (let ((ctl (cdr type-list))
819         (beg 0)
820         (uses-stdin t)
821         out sub total)
822     (while (string-match "%{\\([^}]+\\)}\\|'%s'\\|\"%s\"\\|%s\\|%t\\|%%"
823                          method beg)
824       (push (substring method beg (match-beginning 0)) out)
825       (setq beg (match-end 0)
826             total (match-string 0 method)
827             sub (match-string 1 method))
828       (cond
829        ((string= total "%%")
830         (push "%" out))
831        ((or (string= total "%s")
832             ;; We do our own quoting.
833             (string= total "'%s'")
834             (string= total "\"%s\""))
835         (setq uses-stdin nil)
836         (push (mm-quote-arg
837                (gnus-map-function mm-path-name-rewrite-functions file)) out))
838        ((string= total "%t")
839         (push (mm-quote-arg (car type-list)) out))
840        (t
841         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
842     (push (substring method beg (length method)) out)
843     (when uses-stdin
844       (push "<" out)
845       (push (mm-quote-arg
846              (gnus-map-function mm-path-name-rewrite-functions file))
847             out))
848     (mapconcat 'identity (nreverse out) "")))
849
850 (defun mm-remove-parts (handles)
851   "Remove the displayed MIME parts represented by HANDLES."
852   (if (and (listp handles)
853            (bufferp (car handles)))
854       (mm-remove-part handles)
855     (let (handle)
856       (while (setq handle (pop handles))
857         (cond
858          ((stringp handle)
859           (when (buffer-live-p (get-text-property 0 'buffer handle))
860             (kill-buffer (get-text-property 0 'buffer handle))))
861          ((and (listp handle)
862                (stringp (car handle)))
863           (mm-remove-parts (cdr handle)))
864          (t
865           (mm-remove-part handle)))))))
866
867 (defun mm-destroy-parts (handles)
868   "Remove the displayed MIME parts represented by HANDLES."
869   (if (and (listp handles)
870            (bufferp (car handles)))
871       (mm-destroy-part handles)
872     (let (handle)
873       (while (setq handle (pop handles))
874         (cond
875          ((stringp handle)
876           (when (buffer-live-p (get-text-property 0 'buffer handle))
877             (kill-buffer (get-text-property 0 'buffer handle))))
878          ((and (listp handle)
879                (stringp (car handle)))
880           (mm-destroy-parts handle))
881          (t
882           (mm-destroy-part handle)))))))
883
884 (defun mm-remove-part (handle)
885   "Remove the displayed MIME part represented by HANDLE."
886   (when (listp handle)
887     (let ((object (mm-handle-undisplayer handle)))
888       (ignore-errors
889         (cond
890          ;; Internally displayed part.
891          ((mm-annotationp object)
892           (delete-annotation object))
893          ((or (functionp object)
894               (and (listp object)
895                    (eq (car object) 'lambda)))
896           (funcall object))
897          ;; Externally displayed part.
898          ((consp object)
899           (condition-case ()
900               (while (get-buffer-process (cdr object))
901                 (interrupt-process (get-buffer-process (cdr object)))
902                 (message "Waiting for external displayer to die...")
903                 (sit-for 1))
904             (quit)
905             (error))
906           (ignore-errors (and (cdr object) (kill-buffer (cdr object))))
907           (message "Waiting for external displayer to die...done")
908           (ignore-errors (delete-file (car object)))
909           (ignore-errors (delete-directory (file-name-directory
910                                             (car object)))))
911          ((bufferp object)
912           (when (buffer-live-p object)
913             (kill-buffer object)))))
914       (mm-handle-set-undisplayer handle nil))))
915
916 (defun mm-display-inline (handle)
917   (let* ((type (mm-handle-media-type handle))
918          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
919     (funcall function handle)
920     (goto-char (point-min))))
921
922 (defun mm-assoc-string-match (alist type)
923   (dolist (elem alist)
924     (when (string-match (car elem) type)
925       (return elem))))
926
927 (defun mm-automatic-display-p (handle)
928   "Say whether the user wants HANDLE to be displayed automatically."
929   (let ((methods mm-automatic-display)
930         (type (mm-handle-media-type handle))
931         method result)
932     (while (setq method (pop methods))
933       (when (and (not (mm-inline-override-p handle))
934                  (string-match method type))
935         (setq result t
936               methods nil)))
937     result))
938
939 (defun mm-inlinable-p (handle)
940   "Say whether HANDLE can be displayed inline."
941   (let ((alist mm-inline-media-tests)
942         (type (mm-handle-media-type handle))
943         test)
944     (while alist
945       (when (string-match (caar alist) type)
946         (setq test (caddar alist)
947               alist nil)
948         (setq test (funcall test handle)))
949       (pop alist))
950     test))
951
952 (defun mm-inlined-p (handle)
953   "Say whether the user wants HANDLE to be displayed inline."
954   (let ((methods mm-inlined-types)
955         (type (mm-handle-media-type handle))
956         method result)
957     (while (setq method (pop methods))
958       (when (and (not (mm-inline-override-p handle))
959                  (string-match method type))
960         (setq result t
961               methods nil)))
962     result))
963
964 (defun mm-attachment-override-p (handle)
965   "Say whether HANDLE should have attachment behavior overridden."
966   (let ((types mm-attachment-override-types)
967         (type (mm-handle-media-type handle))
968         ty)
969     (catch 'found
970       (while (setq ty (pop types))
971         (when (and (string-match ty type)
972                    (mm-inlinable-p handle))
973           (throw 'found t))))))
974
975 (defun mm-inline-override-p (handle)
976   "Say whether HANDLE should have inline behavior overridden."
977   (let ((types mm-inline-override-types)
978         (type (mm-handle-media-type handle))
979         ty)
980     (catch 'found
981       (while (setq ty (pop types))
982         (when (string-match ty type)
983           (throw 'found t))))))
984
985 (defun mm-automatic-external-display-p (type)
986   "Return the user-defined method for TYPE."
987   (let ((methods mm-automatic-external-display)
988         method result)
989     (while (setq method (pop methods))
990       (when (string-match method type)
991         (setq result t
992               methods nil)))
993     result))
994
995 (defun mm-destroy-part (handle)
996   "Destroy the data structures connected to HANDLE."
997   (when (listp handle)
998     (mm-remove-part handle)
999     (when (buffer-live-p (mm-handle-buffer handle))
1000       (kill-buffer (mm-handle-buffer handle)))))
1001
1002 (defun mm-handle-displayed-p (handle)
1003   "Say whether HANDLE is displayed or not."
1004   (mm-handle-undisplayer handle))
1005
1006 ;;;
1007 ;;; Functions for outputting parts
1008 ;;;
1009
1010 (defun mm-get-part (handle)
1011   "Return the contents of HANDLE as a string."
1012   (mm-with-unibyte-buffer
1013     (insert (with-current-buffer (mm-handle-buffer handle)
1014               (mm-with-unibyte-current-buffer
1015                 (buffer-string))))
1016     (mm-decode-content-transfer-encoding
1017      (mm-handle-encoding handle)
1018      (mm-handle-media-type handle))
1019     (buffer-string)))
1020
1021 (defun mm-insert-part (handle)
1022   "Insert the contents of HANDLE in the current buffer."
1023   (let ((cur (current-buffer)))
1024     (save-excursion
1025       (if (member (mm-handle-media-supertype handle) '("text" "message"))
1026           (with-temp-buffer
1027             (insert-buffer-substring (mm-handle-buffer handle))
1028             (prog1
1029                 (mm-decode-content-transfer-encoding
1030                  (mm-handle-encoding handle)
1031                  (mm-handle-media-type handle))
1032               (let ((temp (current-buffer)))
1033                 (set-buffer cur)
1034                 (insert-buffer-substring temp))))
1035         (mm-with-unibyte-buffer
1036           (insert-buffer-substring (mm-handle-buffer handle))
1037           (prog1
1038               (mm-decode-content-transfer-encoding
1039                (mm-handle-encoding handle)
1040                (mm-handle-media-type handle))
1041             (let ((temp (current-buffer)))
1042               (set-buffer cur)
1043               (insert-buffer-substring temp))))))))
1044
1045 (defun mm-file-name-delete-whitespace (file-name)
1046   "Remove all whitespace characters from FILE-NAME."
1047   (while (string-match "\\s-+" file-name)
1048     (setq file-name (replace-match "" t t file-name)))
1049   file-name)
1050
1051 (defun mm-file-name-trim-whitespace (file-name)
1052   "Remove leading and trailing whitespace characters from FILE-NAME."
1053   (when (string-match "\\`\\s-+" file-name)
1054     (setq file-name (substring file-name (match-end 0))))
1055   (when (string-match "\\s-+\\'" file-name)
1056     (setq file-name (substring file-name 0 (match-beginning 0))))
1057   file-name)
1058
1059 (defun mm-file-name-collapse-whitespace (file-name)
1060   "Collapse multiple whitespace characters in FILE-NAME."
1061   (while (string-match "\\s-\\s-+" file-name)
1062     (setq file-name (replace-match " " t t file-name)))
1063   file-name)
1064
1065 (defun mm-file-name-replace-whitespace (file-name)
1066   "Replace whitespace characters in FILE-NAME with underscores.
1067 Set the option `mm-file-name-replace-whitespace' to any other
1068 string if you do not like underscores."
1069   (let ((s (or mm-file-name-replace-whitespace "_")))
1070     (while (string-match "\\s-" file-name)
1071       (setq file-name (replace-match s t t file-name))))
1072   file-name)
1073
1074 (defun mm-file-name-delete-control (filename)
1075   "Delete control characters from FILENAME."
1076   (gnus-replace-in-string filename "[\x00-\x1f\x7f]" ""))
1077
1078 (defun mm-file-name-delete-gotchas (filename)
1079   "Delete shell gotchas from FILENAME."
1080   (setq filename (gnus-replace-in-string filename "[<>|]" ""))
1081   (gnus-replace-in-string filename "^[.-]+" ""))
1082
1083 (defun mm-save-part (handle)
1084   "Write HANDLE to a file."
1085   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
1086          (filename (mail-content-type-get
1087                     (mm-handle-disposition handle) 'filename))
1088          file)
1089     (when filename
1090       (setq filename (gnus-map-function mm-file-name-rewrite-functions
1091                                         (file-name-nondirectory filename))))
1092     (setq file
1093           (read-file-name "Save MIME part to: "
1094                           (or mm-default-directory default-directory)
1095                           nil nil (or filename name "")))
1096     (setq mm-default-directory (file-name-directory file))
1097     (and (or (not (file-exists-p file))
1098              (yes-or-no-p (format "File %s already exists; overwrite? "
1099                                   file)))
1100          (progn
1101            (mm-save-part-to-file handle file)
1102            file))))
1103
1104 (defun mm-save-part-to-file (handle file)
1105   (mm-with-unibyte-buffer
1106     (mm-insert-part handle)
1107     (let ((coding-system-for-write 'binary)
1108           (current-file-modes (default-file-modes))
1109           ;; Don't re-compress .gz & al.  Arguably we should make
1110           ;; `file-name-handler-alist' nil, but that would chop
1111           ;; ange-ftp, which is reasonable to use here.
1112           (inhibit-file-name-operation 'write-region)
1113           (inhibit-file-name-handlers
1114            (cons 'jka-compr-handler inhibit-file-name-handlers)))
1115       (set-default-file-modes mm-attachment-file-modes)
1116       (unwind-protect
1117           (write-region (point-min) (point-max) file)
1118         (set-default-file-modes current-file-modes)))))
1119
1120 (defun mm-pipe-part (handle)
1121   "Pipe HANDLE to a process."
1122   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
1123          (command
1124           (read-string "Shell command on MIME part: " mm-last-shell-command)))
1125     (mm-with-unibyte-buffer
1126       (mm-insert-part handle)
1127       (let ((coding-system-for-write 'binary))
1128         (shell-command-on-region (point-min) (point-max) command nil)))))
1129
1130 (defun mm-interactively-view-part (handle)
1131   "Display HANDLE using METHOD."
1132   (let* ((type (mm-handle-media-type handle))
1133          (methods
1134           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
1135                   (mailcap-mime-info type 'all)))
1136          (method (let ((minibuffer-local-completion-map
1137                         mm-viewer-completion-map))
1138                    (completing-read "Viewer: " methods))))
1139     (when (string= method "")
1140       (error "No method given"))
1141     (if (string-match "^[^% \t]+$" method)
1142         (setq method (concat method " %s")))
1143     (mm-display-external handle method)))
1144
1145 (defun mm-preferred-alternative (handles &optional preferred)
1146   "Say which of HANDLES are preferred."
1147   (let ((prec (if preferred (list preferred)
1148                 (mm-preferred-alternative-precedence handles)))
1149         p h result type handle)
1150     (while (setq p (pop prec))
1151       (setq h handles)
1152       (while h
1153         (setq handle (car h))
1154         (setq type (mm-handle-media-type handle))
1155         (when (and (equal p type)
1156                    (mm-automatic-display-p handle)
1157                    (or (stringp (car handle))
1158                        (not (mm-handle-disposition handle))
1159                        (equal (car (mm-handle-disposition handle))
1160                               "inline")))
1161           (setq result handle
1162                 h nil
1163                 prec nil))
1164         (pop h)))
1165     result))
1166
1167 (defun mm-preferred-alternative-precedence (handles)
1168   "Return the precedence based on HANDLES and `mm-discouraged-alternatives'."
1169   (let ((seq (nreverse (mapcar #'mm-handle-media-type
1170                                handles))))
1171     (dolist (disc (reverse mm-discouraged-alternatives))
1172       (dolist (elem (copy-sequence seq))
1173         (when (string-match disc elem)
1174           (setq seq (nconc (delete elem seq) (list elem))))))
1175     seq))
1176
1177 (defun mm-get-content-id (id)
1178   "Return the handle(s) referred to by ID."
1179   (cdr (assoc id mm-content-id-alist)))
1180
1181 (defconst mm-image-type-regexps
1182   '(("/\\*.*XPM.\\*/" . xpm)
1183     ("P[1-6]" . pbm)
1184     ("GIF8" . gif)
1185     ("\377\330" . jpeg)
1186     ("\211PNG\r\n" . png)
1187     ("#define" . xbm)
1188     ("\\(MM\0\\*\\)\\|\\(II\\*\0\\)" . tiff)
1189     ("%!PS" . postscript))
1190   "Alist of (REGEXP . IMAGE-TYPE) pairs used to auto-detect image types.
1191 When the first bytes of an image file match REGEXP, it is assumed to
1192 be of image type IMAGE-TYPE.")
1193
1194 ;; Steal from image.el. image-type-from-data suffers multi-line matching bug.
1195 (defun mm-image-type-from-buffer ()
1196   "Determine the image type from data in the current buffer.
1197 Value is a symbol specifying the image type or nil if type cannot
1198 be determined."
1199   (let ((types mm-image-type-regexps)
1200         type)
1201     (goto-char (point-min))
1202     (while (and types (null type))
1203       (let ((regexp (car (car types)))
1204             (image-type (cdr (car types))))
1205         (when (looking-at regexp)
1206           (setq type image-type))
1207         (setq types (cdr types))))
1208     type))
1209
1210 (defun mm-get-image (handle)
1211   "Return an image instance based on HANDLE."
1212   (let ((type (mm-handle-media-subtype handle))
1213         spec)
1214     ;; Allow some common translations.
1215     (setq type
1216           (cond
1217            ((equal type "x-pixmap")
1218             "xpm")
1219            ((equal type "x-xbitmap")
1220             "xbm")
1221            ((equal type "x-portable-bitmap")
1222             "pbm")
1223            (t type)))
1224     (or (mm-handle-cache handle)
1225         (mm-with-unibyte-buffer
1226           (mm-insert-part handle)
1227           (prog1
1228               (setq spec
1229                     (ignore-errors
1230                       ;; Avoid testing `make-glyph' since W3 may define
1231                       ;; a bogus version of it.
1232                       (if (fboundp 'create-image)
1233                           (create-image (buffer-string)
1234                                         (or (mm-image-type-from-buffer)
1235                                             (intern type))
1236                                         'data-p)
1237                         (mm-create-image-xemacs type))))
1238             (mm-handle-set-cache handle spec))))))
1239
1240 (defun mm-create-image-xemacs (type)
1241   (cond
1242    ((equal type "xbm")
1243     ;; xbm images require special handling, since
1244     ;; the only way to create glyphs from these
1245     ;; (without a ton of work) is to write them
1246     ;; out to a file, and then create a file
1247     ;; specifier.
1248     (let ((file (mm-make-temp-file
1249                  (expand-file-name "emm.xbm"
1250                                    mm-tmp-directory))))
1251       (unwind-protect
1252           (progn
1253             (write-region (point-min) (point-max) file)
1254             (make-glyph (list (cons 'x file))))
1255         (ignore-errors
1256           (delete-file file)))))
1257    (t
1258     (make-glyph
1259      (vector
1260       (or (mm-image-type-from-buffer)
1261           (intern type))
1262       :data (buffer-string))))))
1263
1264 (defun mm-image-fit-p (handle)
1265   "Say whether the image in HANDLE will fit the current window."
1266   (let ((image (mm-get-image handle)))
1267     (if (fboundp 'glyph-width)
1268         ;; XEmacs' glyphs can actually tell us about their width, so
1269         ;; lets be nice and smart about them.
1270         (or mm-inline-large-images
1271             (and (< (glyph-width image) (window-pixel-width))
1272                  (< (glyph-height image) (window-pixel-height))))
1273       (let* ((size (image-size image))
1274              (w (car size))
1275              (h (cdr size)))
1276         (or mm-inline-large-images
1277             (and (< h (1- (window-height))) ; Don't include mode line.
1278                  (< w (window-width))))))))
1279
1280 (defun mm-valid-image-format-p (format)
1281   "Say whether FORMAT can be displayed natively by Emacs."
1282   (cond
1283    ;; Handle XEmacs
1284    ((fboundp 'valid-image-instantiator-format-p)
1285     (valid-image-instantiator-format-p format))
1286    ;; Handle Emacs 21
1287    ((fboundp 'image-type-available-p)
1288     (and (display-graphic-p)
1289          (image-type-available-p format)))
1290    ;; Nobody else can do images yet.
1291    (t
1292     nil)))
1293
1294 (defun mm-valid-and-fit-image-p (format handle)
1295   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
1296   (and (mm-valid-image-format-p format)
1297        (mm-image-fit-p handle)))
1298
1299 (defun mm-find-part-by-type (handles type &optional notp recursive)
1300   "Search in HANDLES for part with TYPE.
1301 If NOTP, returns first non-matching part.
1302 If RECURSIVE, search recursively."
1303   (let (handle)
1304     (while handles
1305       (if (and recursive (stringp (caar handles)))
1306           (if (setq handle (mm-find-part-by-type (cdar handles) type
1307                                                  notp recursive))
1308               (setq handles nil))
1309         (if (if notp
1310                 (not (equal (mm-handle-media-type (car handles)) type))
1311               (equal (mm-handle-media-type (car handles)) type))
1312             (setq handle (car handles)
1313                   handles nil)))
1314       (setq handles (cdr handles)))
1315     handle))
1316
1317 (defun mm-find-raw-part-by-type (ctl type &optional notp)
1318   (goto-char (point-min))
1319   (let* ((boundary (concat "--" (mm-handle-multipart-ctl-parameter ctl
1320                                                                    'boundary)))
1321          (close-delimiter (concat "^" (regexp-quote boundary) "--[ \t]*$"))
1322          start
1323          (end (save-excursion
1324                 (goto-char (point-max))
1325                 (if (re-search-backward close-delimiter nil t)
1326                     (match-beginning 0)
1327                   (point-max))))
1328          result)
1329     (setq boundary (concat "^" (regexp-quote boundary) "[ \t]*$"))
1330     (while (and (not result)
1331                 (re-search-forward boundary end t))
1332       (goto-char (match-beginning 0))
1333       (when start
1334         (save-excursion
1335           (save-restriction
1336             (narrow-to-region start (1- (point)))
1337             (when (let ((ctl (ignore-errors
1338                                (mail-header-parse-content-type
1339                                 (mail-fetch-field "content-type")))))
1340                     (if notp
1341                         (not (equal (car ctl) type))
1342                       (equal (car ctl) type)))
1343               (setq result (buffer-string))))))
1344       (forward-line 1)
1345       (setq start (point)))
1346     (when (and (not result) start)
1347       (save-excursion
1348         (save-restriction
1349           (narrow-to-region start end)
1350           (when (let ((ctl (ignore-errors
1351                              (mail-header-parse-content-type
1352                               (mail-fetch-field "content-type")))))
1353                   (if notp
1354                       (not (equal (car ctl) type))
1355                     (equal (car ctl) type)))
1356             (setq result (buffer-string))))))
1357     result))
1358
1359 (defvar mm-security-handle nil)
1360
1361 (defsubst mm-set-handle-multipart-parameter (handle parameter value)
1362   ;; HANDLE could be a CTL.
1363   (when handle
1364     (put-text-property 0 (length (car handle)) parameter value
1365                        (car handle))))
1366
1367 (defun mm-possibly-verify-or-decrypt (parts ctl)
1368   (let ((type (car ctl))
1369         (subtype (cadr (split-string (car ctl) "/")))
1370         (mm-security-handle ctl) ;; (car CTL) is the type.
1371         protocol func functest)
1372     (cond
1373      ((or (equal type "application/x-pkcs7-mime")
1374           (equal type "application/pkcs7-mime"))
1375       (with-temp-buffer
1376         (when (and (cond
1377                     ((eq mm-decrypt-option 'never) nil)
1378                     ((eq mm-decrypt-option 'always) t)
1379                     ((eq mm-decrypt-option 'known) t)
1380                     (t (y-or-n-p
1381                         (format "Decrypt (S/MIME) part? "))))
1382                    (mm-view-pkcs7 parts))
1383           (setq parts (mm-dissect-buffer t)))))
1384      ((equal subtype "signed")
1385       (unless (and (setq protocol
1386                          (mm-handle-multipart-ctl-parameter ctl 'protocol))
1387                    (not (equal protocol "multipart/mixed")))
1388         ;; The message is broken or draft-ietf-openpgp-multsig-01.
1389         (let ((protocols mm-verify-function-alist))
1390           (while protocols
1391             (if (and (or (not (setq functest (nth 3 (car protocols))))
1392                          (funcall functest parts ctl))
1393                      (mm-find-part-by-type parts (caar protocols) nil t))
1394                 (setq protocol (caar protocols)
1395                       protocols nil)
1396               (setq protocols (cdr protocols))))))
1397       (setq func (nth 1 (assoc protocol mm-verify-function-alist)))
1398       (when (cond
1399              ((eq mm-verify-option 'never) nil)
1400              ((eq mm-verify-option 'always) t)
1401              ((eq mm-verify-option 'known)
1402               (and func
1403                    (or (not (setq functest
1404                                   (nth 3 (assoc protocol
1405                                                 mm-verify-function-alist))))
1406                        (funcall functest parts ctl))))
1407              (t
1408               (y-or-n-p
1409                (format "Verify signed (%s) part? "
1410                        (or (nth 2 (assoc protocol mm-verify-function-alist))
1411                            (format "protocol=%s" protocol))))))
1412         (save-excursion
1413           (if func
1414               (funcall func parts ctl)
1415             (mm-set-handle-multipart-parameter
1416              mm-security-handle 'gnus-details
1417              (format "Unknown sign protocol (%s)" protocol))))))
1418      ((equal subtype "encrypted")
1419       (unless (setq protocol
1420                     (mm-handle-multipart-ctl-parameter ctl 'protocol))
1421         ;; The message is broken.
1422         (let ((parts parts))
1423           (while parts
1424             (if (assoc (mm-handle-media-type (car parts))
1425                        mm-decrypt-function-alist)
1426                 (setq protocol (mm-handle-media-type (car parts))
1427                       parts nil)
1428               (setq parts (cdr parts))))))
1429       (setq func (nth 1 (assoc protocol mm-decrypt-function-alist)))
1430       (when (cond
1431              ((eq mm-decrypt-option 'never) nil)
1432              ((eq mm-decrypt-option 'always) t)
1433              ((eq mm-decrypt-option 'known)
1434               (and func
1435                    (or (not (setq functest
1436                                   (nth 3 (assoc protocol
1437                                                 mm-decrypt-function-alist))))
1438                        (funcall functest parts ctl))))
1439              (t
1440               (y-or-n-p
1441                (format "Decrypt (%s) part? "
1442                        (or (nth 2 (assoc protocol mm-decrypt-function-alist))
1443                            (format "protocol=%s" protocol))))))
1444         (save-excursion
1445           (if func
1446               (setq parts (funcall func parts ctl))
1447             (mm-set-handle-multipart-parameter
1448              mm-security-handle 'gnus-details
1449              (format "Unknown encrypt protocol (%s)" protocol))))))
1450      (t nil))
1451     parts))
1452
1453 (defun mm-multiple-handles (handles)
1454   (and (listp (car handles))
1455        (> (length handles) 1)))
1456
1457 (defun mm-merge-handles (handles1 handles2)
1458   (append
1459    (if (listp (car handles1))
1460        handles1
1461      (list handles1))
1462    (if (listp (car handles2))
1463        handles2
1464      (list handles2))))
1465
1466 (defun mm-readable-p (handle)
1467   "Say whether the content of HANDLE is readable."
1468   (and (< (with-current-buffer (mm-handle-buffer handle)
1469             (buffer-size)) 10000)
1470        (mm-with-unibyte-buffer
1471          (mm-insert-part handle)
1472          (and (eq (mm-body-7-or-8) '7bit)
1473               (not (mm-long-lines-p 76))))))
1474
1475 (provide 'mm-decode)
1476
1477 ;;; mm-decode.el ends here