* mail/rmail.el: Update autoload checksum.
[bpt/emacs.git] / lisp / mail / rmailmm.el
1 ;;; rmailmm.el --- MIME decoding and display stuff for RMAIL
2
3 ;; Copyright (C) 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4
5 ;; Author: Alexander Pohoyda
6 ;; Alex Schroeder
7 ;; Maintainer: FSF
8 ;; Keywords: mail
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; Essentially based on the design of Alexander Pohoyda's MIME
28 ;; extensions (mime-display.el and mime.el).
29 ;; Call `M-x rmail-mime' when viewing an Rmail message.
30
31 ;; Todo:
32
33 ;; Handle multipart/alternative.
34 ;; Offer the option to call external/internal viewers (doc-view, xpdf, etc).
35
36 ;;; Code:
37
38 (require 'rmail)
39 (require 'mail-parse)
40
41 ;;; User options.
42
43 (defgroup rmail-mime nil
44 "Rmail MIME handling options."
45 :prefix "rmail-mime-"
46 :group 'rmail)
47
48 (defcustom rmail-mime-media-type-handlers-alist
49 '(("multipart/.*" rmail-mime-multipart-handler)
50 ("text/.*" rmail-mime-text-handler)
51 ("text/\\(x-\\)?patch" rmail-mime-bulk-handler)
52 ("\\(image\\|audio\\|video\\|application\\)/.*" rmail-mime-bulk-handler))
53 "Functions to handle various content types.
54 This is an alist with elements of the form (REGEXP FUNCTION ...).
55 The first item is a regular expression matching a content-type.
56 The remaining elements are handler functions to run, in order of
57 decreasing preference. These are called until one returns non-nil.
58 Note that this only applies to items with an inline Content-Disposition,
59 all others are handled by `rmail-mime-bulk-handler'."
60 :type '(alist :key-type regexp :value-type (repeat function))
61 :version "23.1"
62 :group 'rmail-mime)
63
64 (defcustom rmail-mime-attachment-dirs-alist
65 `(("text/.*" "~/Documents")
66 ("image/.*" "~/Pictures")
67 (".*" "~/Desktop" "~" ,temporary-file-directory))
68 "Default directories to save attachments of various types into.
69 This is an alist with elements of the form (REGEXP DIR ...).
70 The first item is a regular expression matching a content-type.
71 The remaining elements are directories, in order of decreasing preference.
72 The first directory that exists is used."
73 :type '(alist :key-type regexp :value-type (repeat directory))
74 :version "23.1"
75 :group 'rmail-mime)
76
77 (defcustom rmail-mime-show-images 'button
78 "What to do with image attachments that Emacs is capable of displaying.
79 If nil, do nothing special. If `button', add an extra button
80 that when pushed displays the image in the buffer. If a number,
81 automatically show images if they are smaller than that size (in
82 bytes), otherwise add a display button. Anything else means to
83 automatically display the image in the buffer."
84 :type '(choice (const :tag "Add button to view image" button)
85 (const :tag "No special treatment" nil)
86 (number :tag "Show if smaller than certain size")
87 (other :tag "Always show" show))
88 :version "23.2"
89 :group 'rmail-mime)
90
91 ;;; End of user options.
92
93
94 ;;; Buttons
95
96 (defun rmail-mime-save (button)
97 "Save the attachment using info in the BUTTON."
98 (let* ((filename (button-get button 'filename))
99 (directory (button-get button 'directory))
100 (data (button-get button 'data))
101 (ofilename filename))
102 (setq filename (expand-file-name
103 (read-file-name (format "Save as (default: %s): " filename)
104 directory
105 (expand-file-name filename directory))
106 directory))
107 ;; If arg is just a directory, use the default file name, but in
108 ;; that directory (copied from write-file).
109 (if (file-directory-p filename)
110 (setq filename (expand-file-name
111 (file-name-nondirectory ofilename)
112 (file-name-as-directory filename))))
113 (with-temp-buffer
114 (set-buffer-file-coding-system 'no-conversion)
115 (insert data)
116 (write-region nil nil filename nil nil nil t))))
117
118 (define-button-type 'rmail-mime-save 'action 'rmail-mime-save)
119
120 ;;; Handlers
121
122 (defun rmail-mime-text-handler (content-type
123 content-disposition
124 content-transfer-encoding)
125 "Handle the current buffer as a plain text MIME part."
126 (let* ((charset (cdr (assq 'charset (cdr content-type))))
127 (coding-system (when charset
128 (intern (downcase charset)))))
129 (when (coding-system-p coding-system)
130 (decode-coding-region (point-min) (point-max) coding-system))))
131
132 ;; FIXME move to the test/ directory?
133 (defun test-rmail-mime-handler ()
134 "Test of a mail using no MIME parts at all."
135 (let ((mail "To: alex@gnu.org
136 Content-Type: text/plain; charset=koi8-r
137 Content-Transfer-Encoding: 8bit
138 MIME-Version: 1.0
139
140 \372\304\322\301\327\323\324\327\325\312\324\305\41"))
141 (switch-to-buffer (get-buffer-create "*test*"))
142 (erase-buffer)
143 (set-buffer-multibyte nil)
144 (insert mail)
145 (rmail-mime-show t)
146 (set-buffer-multibyte t)))
147
148
149 (defun rmail-mime-insert-image (type data)
150 "Insert an image of type TYPE, where DATA is the image data."
151 (end-of-line)
152 (insert ?\n)
153 (insert-image (create-image data type t)))
154
155 (defun rmail-mime-image (button)
156 "Display the image associated with BUTTON."
157 (let ((inhibit-read-only t))
158 (rmail-mime-insert-image (button-get button 'image-type)
159 (button-get button 'image-data))))
160
161 (define-button-type 'rmail-mime-image 'action 'rmail-mime-image)
162
163
164 (defun rmail-mime-bulk-handler (content-type
165 content-disposition
166 content-transfer-encoding)
167 "Handle the current buffer as an attachment to download.
168 For images that Emacs is capable of displaying, the behavior
169 depends upon the value of `rmail-mime-show-images'."
170 ;; Find the default directory for this media type.
171 (let* ((directory (catch 'directory
172 (dolist (entry rmail-mime-attachment-dirs-alist)
173 (when (string-match (car entry) (car content-type))
174 (dolist (dir (cdr entry))
175 (when (file-directory-p dir)
176 (throw 'directory dir)))))))
177 (filename (or (cdr (assq 'name (cdr content-type)))
178 (cdr (assq 'filename (cdr content-disposition)))
179 "noname"))
180 (label (format "\nAttached %s file: " (car content-type)))
181 (data (buffer-string))
182 (udata (string-as-unibyte data))
183 (size (length udata))
184 (osize size)
185 (units '(B kB MB GB))
186 type)
187 (while (and (> size 1024.0) ; cribbed from gnus-agent-expire-done-message
188 (cdr units))
189 (setq size (/ size 1024.0)
190 units (cdr units)))
191 (delete-region (point-min) (point-max))
192 (insert label)
193 (insert-button filename
194 :type 'rmail-mime-save
195 'help-echo "mouse-2, RET: Save attachment"
196 'filename filename
197 'directory (file-name-as-directory directory)
198 'data data)
199 (insert (format " (%.0f%s)" size (car units)))
200 (when (and rmail-mime-show-images
201 (string-match "image/\\(.*\\)" (setq type (car content-type)))
202 (setq type (concat "." (match-string 1 type))
203 type (image-type-from-file-name type))
204 (memq type image-types)
205 (image-type-available-p type))
206 (insert " ")
207 (cond ((or (eq rmail-mime-show-images 'button)
208 (and (numberp rmail-mime-show-images)
209 (>= osize rmail-mime-show-images)))
210 (insert-button "Display"
211 :type 'rmail-mime-image
212 'help-echo "mouse-2, RET: Show image"
213 'image-type type
214 'image-data udata))
215 (t
216 (rmail-mime-insert-image type udata))))))
217
218 (defun test-rmail-mime-bulk-handler ()
219 "Test of a mail used as an example in RFC 2183."
220 (let ((mail "Content-Type: image/jpeg
221 Content-Disposition: attachment; filename=genome.jpeg;
222 modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";
223 Content-Description: a complete map of the human genome
224 Content-Transfer-Encoding: base64
225
226 iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAMAAABg3Am1AAAABGdBTUEAALGPC/xhBQAAAAZQ
227 TFRF////AAAAVcLTfgAAAPZJREFUeNq9ldsOwzAIQ+3//+l1WlvA5ZLsoUiTto4TB+ISoAjy
228 +ITfRBfcAmgRFFeAm+J6uhdKdFhFWUgDkFsK0oUp/9G2//Kj7Jx+5tSKOdBscgUYiKHRS/me
229 WATQdRUvAK0Bnmshmtn79PpaLBbbOZkjKvRnjRZoRswOkG1wFchKew2g9wXVJVZL/m4+B+vv
230 9AxQQR2Q33SgAYJzzVACdAWjAfRYzYFO9n6SLnydtQHSMxYDMAKqZ/8FS/lTK+zuq3CtK64L
231 UDwbgUEAUmk2Zyg101d6PhCDySgAvTvDgKiuOrc4dLxUb7UMnhGIexyI+d6U+ABuNAP4Simx
232 lgAAAABJRU5ErkJggg==
233 "))
234 (switch-to-buffer (get-buffer-create "*test*"))
235 (erase-buffer)
236 (insert mail)
237 (rmail-mime-show)))
238
239 (defun rmail-mime-multipart-handler (content-type
240 content-disposition
241 content-transfer-encoding)
242 "Handle the current buffer as a multipart MIME body.
243 The current buffer should be narrowed to the body. CONTENT-TYPE,
244 CONTENT-DISPOSITION, and CONTENT-TRANSFER-ENCODING are the values
245 of the respective parsed headers. See `rmail-mime-handle' for their
246 format."
247 ;; Some MUAs start boundaries with "--", while it should start
248 ;; with "CRLF--", as defined by RFC 2046:
249 ;; The boundary delimiter MUST occur at the beginning of a line,
250 ;; i.e., following a CRLF, and the initial CRLF is considered to
251 ;; be attached to the boundary delimiter line rather than part
252 ;; of the preceding part.
253 ;; We currently don't handle that.
254 (let ((boundary (cdr (assq 'boundary content-type)))
255 beg end next)
256 (unless boundary
257 (rmail-mm-get-boundary-error-message
258 "No boundary defined" content-type content-disposition
259 content-transfer-encoding))
260 (setq boundary (concat "\n--" boundary))
261 ;; Hide the body before the first bodypart
262 (goto-char (point-min))
263 (when (and (search-forward boundary nil t)
264 (looking-at "[ \t]*\n"))
265 (delete-region (point-min) (match-end 0)))
266 ;; Loop over all body parts, where beg points at the beginning of
267 ;; the part and end points at the end of the part. next points at
268 ;; the beginning of the next part.
269 (setq beg (point-min))
270 (while (search-forward boundary nil t)
271 (setq end (match-beginning 0))
272 ;; If this is the last boundary according to RFC 2046, hide the
273 ;; epilogue, else hide the boundary only. Use a marker for
274 ;; `next' because `rmail-mime-show' may change the buffer.
275 (cond ((looking-at "--[ \t]*$")
276 (setq next (point-max-marker)))
277 ((looking-at "[ \t]*\n")
278 (setq next (copy-marker (match-end 0) t)))
279 (t
280 (rmail-mm-get-boundary-error-message
281 "Malformed boundary" content-type content-disposition
282 content-transfer-encoding)))
283 (delete-region end next)
284 ;; Handle the part.
285 (save-restriction
286 (narrow-to-region beg end)
287 (rmail-mime-show))
288 (goto-char (setq beg next)))))
289
290
291 (defun test-rmail-mime-multipart-handler ()
292 "Test of a mail used as an example in RFC 2046."
293 (let ((mail "From: Nathaniel Borenstein <nsb@bellcore.com>
294 To: Ned Freed <ned@innosoft.com>
295 Date: Sun, 21 Mar 1993 23:56:48 -0800 (PST)
296 Subject: Sample message
297 MIME-Version: 1.0
298 Content-type: multipart/mixed; boundary=\"simple boundary\"
299
300 This is the preamble. It is to be ignored, though it
301 is a handy place for composition agents to include an
302 explanatory note to non-MIME conformant readers.
303
304 --simple boundary
305
306 This is implicitly typed plain US-ASCII text.
307 It does NOT end with a linebreak.
308 --simple boundary
309 Content-type: text/plain; charset=us-ascii
310
311 This is explicitly typed plain US-ASCII text.
312 It DOES end with a linebreak.
313
314 --simple boundary--
315
316 This is the epilogue. It is also to be ignored."))
317 (switch-to-buffer (get-buffer-create "*test*"))
318 (erase-buffer)
319 (insert mail)
320 (rmail-mime-show t)))
321
322 ;;; Main code
323
324 (defun rmail-mime-handle (content-type
325 content-disposition
326 content-transfer-encoding)
327 "Handle the current buffer as a MIME part.
328 The current buffer should be narrowed to the respective body, and
329 point should be at the beginning of the body.
330
331 CONTENT-TYPE, CONTENT-DISPOSITION, and CONTENT-TRANSFER-ENCODING
332 are the values of the respective parsed headers. The latter should
333 be downcased. The parsed headers for CONTENT-TYPE and CONTENT-DISPOSITION
334 have the form
335
336 \(VALUE . ALIST)
337
338 In other words:
339
340 \(VALUE (ATTRIBUTE . VALUE) (ATTRIBUTE . VALUE) ...)
341
342 VALUE is a string and ATTRIBUTE is a symbol.
343
344 Consider the following header, for example:
345
346 Content-Type: multipart/mixed;
347 boundary=\"----=_NextPart_000_0104_01C617E4.BDEC4C40\"
348
349 The parsed header value:
350
351 \(\"multipart/mixed\"
352 \(\"boundary\" . \"----=_NextPart_000_0104_01C617E4.BDEC4C40\"))"
353 ;; Handle the content transfer encodings we know. Unknown transfer
354 ;; encodings will be passed on to the various handlers.
355 (cond ((string= content-transfer-encoding "base64")
356 (when (ignore-errors
357 (base64-decode-region (point) (point-max)))
358 (setq content-transfer-encoding nil)))
359 ((string= content-transfer-encoding "quoted-printable")
360 (quoted-printable-decode-region (point) (point-max))
361 (setq content-transfer-encoding nil))
362 ((string= content-transfer-encoding "8bit")
363 ;; FIXME: Is this the correct way?
364 ;; No, of course not, it just means there's no decoding to do.
365 ;; (set-buffer-multibyte nil)
366 (setq content-transfer-encoding nil)
367 ))
368 ;; Inline stuff requires work. Attachments are handled by the bulk
369 ;; handler.
370 (if (string= "inline" (car content-disposition))
371 (let ((stop nil))
372 (dolist (entry rmail-mime-media-type-handlers-alist)
373 (when (and (string-match (car entry) (car content-type)) (not stop))
374 (progn
375 (setq stop (funcall (cadr entry) content-type
376 content-disposition
377 content-transfer-encoding))))))
378 ;; Everything else is an attachment.
379 (rmail-mime-bulk-handler content-type
380 content-disposition
381 content-transfer-encoding)))
382
383 (defun rmail-mime-show (&optional show-headers)
384 "Handle the current buffer as a MIME message.
385 If SHOW-HEADERS is non-nil, then the headers of the current part
386 will shown as usual for a MIME message. The headers are also
387 shown for the content type message/rfc822. This function will be
388 called recursively if multiple parts are available.
389
390 The current buffer must contain a single message. It will be
391 modified."
392 (let ((end (point-min))
393 content-type
394 content-transfer-encoding
395 content-disposition)
396 ;; `point-min' returns the beginning and `end' points at the end
397 ;; of the headers.
398 (goto-char (point-min))
399 ;; If we're showing a part without headers, then it will start
400 ;; with a newline.
401 (if (eq (char-after) ?\n)
402 (setq end (1+ (point)))
403 (when (search-forward "\n\n" nil t)
404 (setq end (match-end 0))
405 (save-restriction
406 (narrow-to-region (point-min) end)
407 ;; FIXME: Default disposition of the multipart entities should
408 ;; be inherited.
409 (setq content-type
410 (mail-fetch-field "Content-Type")
411 content-transfer-encoding
412 (mail-fetch-field "Content-Transfer-Encoding")
413 content-disposition
414 (mail-fetch-field "Content-Disposition")))))
415 ;; Per RFC 2045, C-T-E is case insensitive (bug#5070), but the others
416 ;; are not completely so. Hopefully mail-header-parse-* DTRT.
417 (if content-transfer-encoding
418 (setq content-transfer-encoding (downcase content-transfer-encoding)))
419 (setq content-type
420 (if content-type
421 (mail-header-parse-content-type content-type)
422 ;; FIXME: Default "message/rfc822" in a "multipart/digest"
423 ;; according to RFC 2046.
424 '("text/plain")))
425 (setq content-disposition
426 (if content-disposition
427 (mail-header-parse-content-disposition content-disposition)
428 ;; If none specified, we are free to choose what we deem
429 ;; suitable according to RFC 2183. We like inline.
430 '("inline")))
431 ;; Unrecognized disposition types are to be treated like
432 ;; attachment according to RFC 2183.
433 (unless (member (car content-disposition) '("inline" "attachment"))
434 (setq content-disposition '("attachment")))
435 ;; Hide headers and handle the part.
436 (save-restriction
437 (cond ((string= (car content-type) "message/rfc822")
438 (narrow-to-region end (point-max)))
439 ((not show-headers)
440 (delete-region (point-min) end)))
441 (rmail-mime-handle content-type content-disposition
442 content-transfer-encoding))))
443
444 (define-derived-mode rmail-mime-mode fundamental-mode "RMIME"
445 "Major mode used in `rmail-mime' buffers."
446 (setq font-lock-defaults '(rmail-font-lock-keywords t t nil nil)))
447
448 ;;;###autoload
449 (defun rmail-mime ()
450 "Process the current Rmail message as a MIME message.
451 This creates a temporary \"*RMAIL*\" buffer holding a decoded
452 copy of the message. Inline content-types are handled according to
453 `rmail-mime-media-type-handlers-alist'. By default, this
454 displays text and multipart messages, and offers to download
455 attachments as specfied by `rmail-mime-attachment-dirs-alist'."
456 (interactive)
457 (let ((data (rmail-apply-in-message rmail-current-message 'buffer-string))
458 (buf (get-buffer-create "*RMAIL*")))
459 (set-buffer buf)
460 (setq buffer-undo-list t)
461 (let ((inhibit-read-only t))
462 ;; Decoding the message in fundamental mode for speed, only
463 ;; switching to rmail-mime-mode at the end for display. Eg
464 ;; quoted-printable-decode-region gets very slow otherwise (Bug#4993).
465 (fundamental-mode)
466 (erase-buffer)
467 (insert data)
468 (rmail-mime-show t)
469 (rmail-mime-mode)
470 (set-buffer-modified-p nil))
471 (view-buffer buf)))
472
473 (defun rmail-mm-get-boundary-error-message (message type disposition encoding)
474 "Return MESSAGE with more information on the main mime components."
475 (error "%s; type: %s; disposition: %s; encoding: %s"
476 message type disposition encoding))
477
478 (provide 'rmailmm)
479
480 ;; Local Variables:
481 ;; generated-autoload-file: "rmail.el"
482 ;; End:
483
484 ;; arch-tag: 3f2c5e5d-1aef-4512-bc20-fd737c9d5dd9
485 ;;; rmailmm.el ends here