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