90a73582585a81c2cb567f97d4ba8b1dfcc98c26
[elisp/gnus.git-] / lisp / mm-view.el
1 ;;; mm-view.el --- functions for viewing MIME objects
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; This file is part of GNU Emacs.
6
7 ;; GNU Emacs is free software; you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation; either version 2, or (at your option)
10 ;; any later version.
11
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ;; GNU General Public License for more details.
16
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
19 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 ;; Boston, MA 02111-1307, USA.
21
22 ;;; Commentary:
23
24 ;;; Code:
25
26 (eval-when-compile (require 'cl))
27 (require 'mail-parse)
28 (require 'mailcap)
29 (require 'mm-bodies)
30 (require 'mm-decode)
31
32 (eval-and-compile
33   (autoload 'gnus-article-prepare-display "gnus-art")
34   (autoload 'vcard-parse-string "vcard")
35   (autoload 'vcard-format-string "vcard")
36   (autoload 'fill-flowed "flow-fill")
37   (autoload 'html2text "html2text")
38   (unless (fboundp 'diff-mode)
39     (autoload 'diff-mode "diff-mode" "" t nil)))
40
41 (defvar mm-text-html-renderer-alist
42   '((w3  . mm-inline-text-html-render-with-w3)
43     (w3m . mm-inline-text-html-render-with-w3m)
44     (w3m-standalone mm-inline-render-with-stdin nil
45                     "w3m" "-dump" "-T" "text/html")
46     (links mm-inline-render-with-file
47            mm-links-remove-leading-blank
48            "links" "-dump" file)
49     (lynx  mm-inline-render-with-stdin nil
50            "lynx" "-dump" "-force_html" "-stdin")
51     (html2text  mm-inline-render-with-function html2text))
52   "The attributes of renderer types for text/html.")
53
54 (defvar mm-text-html-washer-alist
55   '((w3  . gnus-article-wash-html-with-w3)
56     (w3m . gnus-article-wash-html-with-w3m)
57     (w3m-standalone mm-inline-render-with-stdin nil
58                     "w3m" "-dump" "-T" "text/html")
59     (links mm-inline-wash-with-file
60            mm-links-remove-leading-blank
61            "links" "-dump" file)
62     (lynx  mm-inline-wash-with-stdin nil
63            "lynx" "-dump" "-force_html" "-stdin")
64     (html2text  html2text))
65   "The attributes of washer types for text/html.")
66
67 ;;; Internal variables.
68
69 ;;;
70 ;;; Functions for displaying various formats inline
71 ;;;
72
73 (defun mm-inline-image-emacs (handle)
74   (let ((b (point-marker))
75         buffer-read-only)
76     (insert "\n")
77     (put-image (mm-get-image handle) b)
78     (mm-handle-set-undisplayer
79      handle
80      `(lambda () (remove-images ,b (1+ ,b))))))
81
82 (defun mm-inline-image-xemacs (handle)
83   (insert "\n")
84   (forward-char -1)
85   (let ((b (point))
86         (annot (make-annotation (mm-get-image handle) nil 'text))
87         buffer-read-only)
88     (mm-handle-set-undisplayer
89      handle
90      `(lambda ()
91         (let (buffer-read-only)
92           (delete-annotation ,annot)
93           (delete-region ,(set-marker (make-marker) b)
94                          ,(set-marker (make-marker) (point))))))
95     (set-extent-property annot 'mm t)
96     (set-extent-property annot 'duplicable t)))
97
98 (eval-and-compile
99   (if (featurep 'xemacs)
100       (defalias 'mm-inline-image 'mm-inline-image-xemacs)
101     (defalias 'mm-inline-image 'mm-inline-image-emacs)))
102
103 (defvar mm-w3-setup nil)
104 (defun mm-setup-w3 ()
105   (unless mm-w3-setup
106     (require 'w3)
107     (w3-do-setup)
108     (require 'url)
109     (require 'w3-vars)
110     (require 'url-vars)
111     (setq mm-w3-setup t)))
112
113 (defun mm-inline-text-html-render-with-w3 (handle)
114   (mm-setup-w3)
115   (let ((text (mm-get-part handle))
116         (b (point))
117         (url-standalone-mode t)
118         (url-gateway-unplugged t)
119         (w3-honor-stylesheets nil)
120         (url-current-object
121          (url-generic-parse-url (format "cid:%s" (mm-handle-id handle))))
122         (width (window-width))
123         (charset (mail-content-type-get
124                   (mm-handle-type handle) 'charset)))
125     (save-excursion
126       (insert text)
127       (save-restriction
128         (narrow-to-region b (point))
129         (goto-char (point-min))
130         (if (or (and (boundp 'w3-meta-content-type-charset-regexp)
131                      (re-search-forward
132                       w3-meta-content-type-charset-regexp nil t))
133                 (and (boundp 'w3-meta-charset-content-type-regexp)
134                      (re-search-forward
135                       w3-meta-charset-content-type-regexp nil t)))
136             (setq charset
137                   (or (let ((bsubstr (buffer-substring-no-properties
138                                       (match-beginning 2)
139                                       (match-end 2))))
140                         (if (fboundp 'w3-coding-system-for-mime-charset)
141                             (w3-coding-system-for-mime-charset bsubstr)
142                           (mm-charset-to-coding-system bsubstr)))
143                       charset)))
144         (delete-region (point-min) (point-max))
145         (insert (mm-decode-string text charset))
146         (save-window-excursion
147           (save-restriction
148             (let ((w3-strict-width width)
149                   ;; Don't let w3 set the global version of
150                   ;; this variable.
151                   (fill-column fill-column))
152               (if (or debug-on-error debug-on-quit)
153                   (w3-region (point-min) (point-max))
154                 (condition-case ()
155                     (w3-region (point-min) (point-max))
156                   (error
157                    (delete-region (point-min) (point-max))
158                    (let ((b (point))
159                          (charset (mail-content-type-get
160                                    (mm-handle-type handle) 'charset)))
161                      (if (or (eq charset 'gnus-decoded)
162                              (eq mail-parse-charset 'gnus-decoded))
163                        (save-restriction
164                          (narrow-to-region (point) (point))
165                          (mm-insert-part handle)
166                          (goto-char (point-max)))
167                        (insert (mm-decode-string (mm-get-part handle)
168                                                  charset))))
169                    (message
170                     "Error while rendering html; showing as text/plain")))))))
171         (mm-handle-set-undisplayer
172          handle
173          `(lambda ()
174             (let (buffer-read-only)
175               (if (functionp 'remove-specifier)
176                   (mapcar (lambda (prop)
177                             (remove-specifier
178                              (face-property 'default prop)
179                              (current-buffer)))
180                           '(background background-pixmap foreground)))
181               (delete-region ,(point-min-marker)
182                              ,(point-max-marker)))))))))
183
184 (defvar mm-w3m-setup nil
185   "Whether gnus-article-mode has been setup to use emacs-w3m.")
186
187 (defun mm-setup-w3m ()
188   "Setup gnus-article-mode to use emacs-w3m."
189   (unless mm-w3m-setup
190     (require 'w3m)
191     (unless (assq 'gnus-article-mode w3m-cid-retrieve-function-alist)
192       (push (cons 'gnus-article-mode 'mm-w3m-cid-retrieve)
193             w3m-cid-retrieve-function-alist))
194     (setq mm-w3m-setup t)))
195
196 (defun mm-w3m-cid-retrieve (url &rest args)
197   "Insert a content pointed by URL if it has the cid: scheme."
198   (when (string-match "\\`cid:" url)
199     (setq url (concat "<" (substring url (match-end 0)) ">"))
200     (catch 'found-handle
201       (dolist (handle (with-current-buffer w3m-current-buffer
202                         gnus-article-mime-handles))
203         (when (and (listp handle)
204                    (equal url (mm-handle-id handle)))
205           (mm-insert-part handle)
206           (throw 'found-handle (mm-handle-media-type handle)))))))
207
208 (eval-and-compile
209   (unless (or (featurep 'xemacs)
210               (>= emacs-major-version 21))
211     (defvar mm-w3m-mode-map nil
212       "Keymap for text/html part rendered by `mm-w3m-preview-text/html'.
213 This map is overwritten by `mm-w3m-local-map-property' based on the
214 value of `w3m-minor-mode-map'.  Therefore, in order to add some
215 commands to this map, add them to `w3m-minor-mode-map' instead of this
216 map.")))
217
218 (defun mm-w3m-local-map-property ()
219   (when (and (boundp 'w3m-minor-mode-map) w3m-minor-mode-map)
220     (if (or (featurep 'xemacs)
221             (>= emacs-major-version 21))
222         (list 'keymap w3m-minor-mode-map)
223       (list 'local-map
224             (or mm-w3m-mode-map
225                 (progn
226                   (setq mm-w3m-mode-map (copy-keymap w3m-minor-mode-map))
227                   (set-keymap-parent mm-w3m-mode-map gnus-article-mode-map)
228                   mm-w3m-mode-map))))))
229
230 (defun mm-inline-text-html-render-with-w3m (handle)
231   "Render a text/html part using emacs-w3m."
232   (mm-setup-w3m)
233   (let ((text (mm-get-part handle))
234         (b (point))
235         (charset (mail-content-type-get (mm-handle-type handle) 'charset)))
236     (save-excursion
237       (insert text)
238       (save-restriction
239         (narrow-to-region b (point))
240         (goto-char (point-min))
241         (when (re-search-forward w3m-meta-content-type-charset-regexp nil t)
242           (setq charset (or (w3m-charset-to-coding-system (match-string 2))
243                             charset)))
244         (when charset
245           (delete-region (point-min) (point-max))
246           (insert (mm-decode-string text charset)))
247         (let ((w3m-safe-url-regexp mm-w3m-safe-url-regexp)
248               (w3m-display-inline-images mm-inline-text-html-with-images)
249               w3m-force-redisplay)
250           (w3m-region (point-min) (point-max)))
251         (when mm-inline-text-html-with-w3m-keymap
252           (add-text-properties
253            (point-min) (point-max)
254            (nconc (mm-w3m-local-map-property)
255                   '(mm-inline-text-html-with-w3m t)))))
256       (mm-handle-set-undisplayer
257        handle
258        `(lambda ()
259           (let (buffer-read-only)
260             (if (functionp 'remove-specifier)
261                 (mapcar (lambda (prop)
262                           (remove-specifier
263                            (face-property 'default prop)
264                            (current-buffer)))
265                         '(background background-pixmap foreground)))
266             (delete-region ,(point-min-marker)
267                            ,(point-max-marker))))))))
268
269 (defun mm-links-remove-leading-blank ()
270   ;; Delete the annoying three spaces preceding each line of links
271   ;; output.
272   (goto-char (point-min))
273   (while (re-search-forward "^   " nil t)
274     (delete-region (match-beginning 0) (match-end 0))))
275
276 (defun mm-inline-wash-with-file (post-func cmd &rest args)
277   (let ((file (mm-make-temp-file
278                (expand-file-name "mm" mm-tmp-directory))))
279     (let ((coding-system-for-write 'binary))
280       (write-region (point-min) (point-max) file nil 'silent))
281     (delete-region (point-min) (point-max))
282     (unwind-protect
283         (apply 'call-process cmd nil t nil (mapcar 'eval args))
284       (delete-file file))
285     (and post-func (funcall post-func))))
286
287 (defun mm-inline-wash-with-stdin (post-func cmd &rest args)
288   (let ((coding-system-for-write 'binary))
289     (apply 'call-process-region (point-min) (point-max)
290            cmd t t nil args))
291   (and post-func (funcall post-func)))
292
293 (defun mm-inline-render-with-file (handle post-func cmd &rest args)
294   (let ((source (mm-get-part handle)))
295     (mm-insert-inline
296      handle
297      (mm-with-unibyte-buffer
298        (insert source)
299        (apply 'mm-inline-wash-with-file post-func cmd args)
300        (buffer-string)))))
301
302 (defun mm-inline-render-with-stdin (handle post-func cmd &rest args)
303   (let ((source (mm-get-part handle)))
304     (mm-insert-inline
305      handle
306      (mm-with-unibyte-buffer
307        (insert source)
308        (apply 'mm-inline-wash-with-stdin post-func cmd args)
309        (buffer-string)))))
310
311 (defun mm-inline-render-with-function (handle func &rest args)
312   (let ((source (mm-get-part handle)))
313     (mm-insert-inline
314      handle
315      (mm-with-unibyte-buffer
316        (insert source)
317        (apply func args)
318        (buffer-string)))))
319
320 (defun mm-inline-text-html (handle)
321   (let* ((func (or mm-inline-text-html-renderer mm-text-html-renderer))
322          (entry (assq func mm-text-html-renderer-alist))
323          buffer-read-only)
324     (if entry
325         (setq func (cdr entry)))
326     (cond
327      ((gnus-functionp func)
328       (funcall func handle))
329      (t
330       (apply (car func) handle (cdr func))))))
331
332 (defun mm-inline-text-vcard (handle)
333   (let (buffer-read-only)
334     (mm-insert-inline
335      handle
336      (concat "\n-- \n"
337              (ignore-errors
338                (if (fboundp 'vcard-pretty-print)
339                    (vcard-pretty-print (mm-get-part handle))
340                  (vcard-format-string
341                   (vcard-parse-string (mm-get-part handle)
342                                       'vcard-standard-filter))))))))
343
344 (defun mm-inline-text (handle)
345   (let ((b (point))
346         (type (mm-handle-media-subtype handle))
347         (charset (mail-content-type-get
348                   (mm-handle-type handle) 'charset))
349         buffer-read-only)
350     (if (or (eq charset 'gnus-decoded)
351             ;; This is probably not entirely correct, but
352             ;; makes rfc822 parts with embedded multiparts work.
353             (eq mail-parse-charset 'gnus-decoded))
354         (save-restriction
355           (narrow-to-region (point) (point))
356           (mm-insert-part handle)
357           (goto-char (point-max)))
358       (insert (mm-decode-string (mm-get-part handle) charset)))
359     (when (and (equal type "plain")
360                (equal (cdr (assoc 'format (mm-handle-type handle)))
361                       "flowed"))
362       (save-restriction
363         (narrow-to-region b (point))
364         (goto-char b)
365         (fill-flowed)
366         (goto-char (point-max))))
367     (save-restriction
368       (narrow-to-region b (point))
369       (set-text-properties (point-min) (point-max) nil)
370       (when (or (equal type "enriched")
371                 (equal type "richtext"))
372         (enriched-decode (point-min) (point-max)))
373       (mm-handle-set-undisplayer
374        handle
375        `(lambda ()
376           (let (buffer-read-only)
377             (delete-region ,(point-min-marker)
378                            ,(point-max-marker))))))))
379
380 (defun mm-insert-inline (handle text)
381   "Insert TEXT inline from HANDLE."
382   (let ((b (point)))
383     (insert text)
384     (mm-handle-set-undisplayer
385      handle
386      `(lambda ()
387         (let (buffer-read-only)
388           (delete-region ,(set-marker (make-marker) b)
389                          ,(set-marker (make-marker) (point))))))))
390
391 (defun mm-inline-audio (handle)
392   (message "Not implemented"))
393
394 (defun mm-view-sound-file ()
395   (message "Not implemented"))
396
397 (defun mm-w3-prepare-buffer ()
398   (require 'w3)
399   (let ((url-standalone-mode t)
400         (url-gateway-unplugged t)
401         (w3-honor-stylesheets nil))
402     (w3-prepare-buffer)))
403
404 (defun mm-view-message ()
405   (mm-enable-multibyte)
406   (let (handles)
407     (let (gnus-article-mime-handles)
408       ;; Double decode problem may happen.  See mm-inline-message.
409       (run-hooks 'gnus-article-decode-hook)
410       (gnus-article-prepare-display)
411       (setq handles gnus-article-mime-handles))
412     (when handles
413       (setq gnus-article-mime-handles
414             (mm-merge-handles gnus-article-mime-handles handles))))
415   (fundamental-mode)
416   (goto-char (point-min)))
417
418 (defun mm-inline-message (handle)
419   (let ((b (point))
420         (bolp (bolp))
421         (charset (mail-content-type-get
422                   (mm-handle-type handle) 'charset))
423         gnus-displaying-mime handles)
424     (when (and charset
425                (stringp charset))
426       (setq charset (intern (downcase charset)))
427       (when (eq charset 'us-ascii)
428         (setq charset nil)))
429     (save-excursion
430       (save-restriction
431         (narrow-to-region b b)
432         (mm-insert-part handle)
433         (let (gnus-article-mime-handles
434               ;; disable prepare hook
435               gnus-article-prepare-hook
436               (gnus-newsgroup-charset
437                (or charset gnus-newsgroup-charset)))
438           (run-hooks 'gnus-article-decode-hook)
439           (gnus-article-prepare-display)
440           (setq handles gnus-article-mime-handles))
441         (goto-char (point-min))
442         (unless bolp
443           (insert "\n"))
444         (goto-char (point-max))
445         (unless (bolp)
446           (insert "\n"))
447         (insert "----------\n\n")
448         (when handles
449           (setq gnus-article-mime-handles
450                 (mm-merge-handles gnus-article-mime-handles handles)))
451         (mm-handle-set-undisplayer
452          handle
453          `(lambda ()
454             (let (buffer-read-only)
455               (if (fboundp 'remove-specifier)
456                   ;; This is only valid on XEmacs.
457                   (mapcar (lambda (prop)
458                             (remove-specifier
459                              (face-property 'default prop) (current-buffer)))
460                           '(background background-pixmap foreground)))
461               (delete-region ,(point-min-marker) ,(point-max-marker)))))))))
462
463 (defun mm-display-inline-fontify (handle mode)
464   (let (text)
465     ;; XEmacs @#$@ version of font-lock refuses to fully turn itself
466     ;; on for buffers whose name begins with " ".  That's why we use
467     ;; save-current-buffer/get-buffer-create rather than
468     ;; with-temp-buffer.
469     (save-current-buffer
470       (set-buffer (generate-new-buffer "*fontification*"))
471       (unwind-protect
472           (progn
473             (buffer-disable-undo)
474             (mm-insert-part handle)
475             (funcall mode)
476             (require 'font-lock)
477             (let ((font-lock-verbose nil))
478               ;; I find font-lock a bit too verbose.
479               (font-lock-fontify-buffer))
480             ;; By default, XEmacs font-lock uses non-duplicable text
481             ;; properties.  This code forces all the text properties
482             ;; to be copied along with the text.
483             (when (fboundp 'extent-list)
484               (map-extents (lambda (ext ignored)
485                              (set-extent-property ext 'duplicable t)
486                              nil)
487                            nil nil nil nil nil 'text-prop))
488             (setq text (buffer-string)))
489         (kill-buffer (current-buffer))))
490     (mm-insert-inline handle text)))
491
492 ;; Shouldn't these functions check whether the user even wants to use
493 ;; font-lock?  At least under XEmacs, this fontification is pretty
494 ;; much unconditional.  Also, it would be nice to change for the size
495 ;; of the fontified region.
496
497 (defun mm-display-patch-inline (handle)
498   (mm-display-inline-fontify handle 'diff-mode))
499
500 (defun mm-display-elisp-inline (handle)
501   (mm-display-inline-fontify handle 'emacs-lisp-mode))
502
503 ;;      id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
504 ;;          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }
505 (defvar mm-pkcs7-signed-magic
506   (mm-string-as-unibyte
507    (apply 'concat
508           (mapcar 'char-to-string
509                   (list ?\x30 ?\x5c ?\x28 ?\x80 ?\x5c ?\x7c ?\x81 ?\x2e ?\x5c
510                         ?\x7c ?\x82 ?\x2e ?\x2e ?\x5c ?\x7c ?\x83 ?\x2e ?\x2e
511                         ?\x2e ?\x5c ?\x29 ?\x06 ?\x09 ?\x5c ?\x2a ?\x86 ?\x48
512                         ?\x86 ?\xf7 ?\x0d ?\x01 ?\x07 ?\x02)))))
513
514 ;;      id-envelopedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
515 ;;          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 3 }
516 (defvar mm-pkcs7-enveloped-magic
517   (mm-string-as-unibyte
518    (apply 'concat
519           (mapcar 'char-to-string
520                   (list ?\x30 ?\x5c ?\x28 ?\x80 ?\x5c ?\x7c ?\x81 ?\x2e ?\x5c
521                         ?\x7c ?\x82 ?\x2e ?\x2e ?\x5c ?\x7c ?\x83 ?\x2e ?\x2e
522                         ?\x2e ?\x5c ?\x29 ?\x06 ?\x09 ?\x5c ?\x2a ?\x86 ?\x48
523                         ?\x86 ?\xf7 ?\x0d ?\x01 ?\x07 ?\x03)))))
524
525 (defun mm-view-pkcs7-get-type (handle)
526   (mm-with-unibyte-buffer
527     (mm-insert-part handle)
528     (cond ((looking-at mm-pkcs7-enveloped-magic)
529            'enveloped)
530           ((looking-at mm-pkcs7-signed-magic)
531            'signed)
532           (t
533            (error "Could not identify PKCS#7 type")))))
534
535 (defun mm-view-pkcs7 (handle)
536   (case (mm-view-pkcs7-get-type handle)
537     (enveloped (mm-view-pkcs7-decrypt handle))
538     (signed (mm-view-pkcs7-verify handle))
539     (otherwise (error "Unknown or unimplemented PKCS#7 type"))))
540
541 (defun mm-view-pkcs7-verify (handle)
542   ;; A bogus implementation of PKCS#7. FIXME::
543   (mm-insert-part handle)
544   (goto-char (point-min))
545   (if (search-forward "Content-Type: " nil t)
546       (delete-region (point-min) (match-beginning 0)))
547   (goto-char (point-max))
548   (if (re-search-backward "--\r?\n?" nil t)
549       (delete-region (match-end 0) (point-max)))
550   (goto-char (point-min))
551   (while (search-forward "\r\n" nil t)
552     (replace-match "\n"))
553   (message "Verify signed PKCS#7 message is unimplemented.")
554   (sit-for 1)
555   t)
556
557 (defun mm-view-pkcs7-decrypt (handle)
558   (insert-buffer (mm-handle-buffer handle))
559   (goto-char (point-min))
560   (insert "MIME-Version: 1.0\n")
561   (mm-insert-headers "application/pkcs7-mime" "base64" "smime.p7m")
562   (smime-decrypt-region
563    (point-min) (point-max)
564    (if (= (length smime-keys) 1)
565        (cadar smime-keys)
566      (smime-get-key-by-email
567       (completing-read
568        (concat "Decipher using which key? "
569                (if smime-keys (concat "(default " (caar smime-keys) ") ")
570                  ""))
571        smime-keys nil nil nil nil (car-safe (car-safe smime-keys))))))
572   (goto-char (point-min))
573   (while (search-forward "\r\n" nil t)
574     (replace-match "\n"))
575   (goto-char (point-min)))
576
577 (provide 'mm-view)
578
579 ;;; mm-view.el ends here