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