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