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