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