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