* lpath.el: Bind w3m-minor-mode-map.
[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   (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   (if (or (featurep 'xemacs)
220           (>= emacs-major-version 21))
221       (list 'keymap w3m-minor-mode-map)
222     (list 'local-map
223           (or mm-w3m-mode-map
224               (progn
225                 (setq mm-w3m-mode-map (copy-keymap w3m-minor-mode-map))
226                 (set-keymap-parent mm-w3m-mode-map gnus-article-mode-map)
227                 mm-w3m-mode-map)))))
228
229 (defun mm-inline-text-html-render-with-w3m (handle)
230   "Render a text/html part using emacs-w3m."
231   (mm-setup-w3m)
232   (let ((text (mm-get-part handle))
233         (b (point))
234         (charset (mail-content-type-get (mm-handle-type handle) 'charset)))
235     (save-excursion
236       (insert text)
237       (save-restriction
238         (narrow-to-region b (point))
239         (goto-char (point-min))
240         (when (re-search-forward w3m-meta-content-type-charset-regexp nil t)
241           (setq charset (or (w3m-charset-to-coding-system (match-string 2))
242                             charset)))
243         (when charset
244           (delete-region (point-min) (point-max))
245           (insert (mm-decode-string text charset)))
246         (let ((w3m-safe-url-regexp mm-w3m-safe-url-regexp)
247               (w3m-display-inline-images mm-inline-text-html-with-images)
248               w3m-force-redisplay)
249           (w3m-region (point-min) (point-max)))
250         (when mm-inline-text-html-with-w3m-keymap
251           (add-text-properties
252            (point-min) (point-max)
253            (nconc (mm-w3m-local-map-property)
254                   '(mm-inline-text-html-with-w3m t)))))
255       (mm-handle-set-undisplayer
256        handle
257        `(lambda ()
258           (let (buffer-read-only)
259             (if (functionp 'remove-specifier)
260                 (mapcar (lambda (prop)
261                           (remove-specifier
262                            (face-property 'default prop)
263                            (current-buffer)))
264                         '(background background-pixmap foreground)))
265             (delete-region ,(point-min-marker)
266                            ,(point-max-marker))))))))
267
268 (defun mm-links-remove-leading-blank ()
269   ;; Delete the annoying three spaces preceding each line of links
270   ;; output.
271   (goto-char (point-min))
272   (while (re-search-forward "^   " nil t)
273     (delete-region (match-beginning 0) (match-end 0))))
274
275 (defun mm-inline-wash-with-file (post-func cmd &rest args)
276   (let ((file (mm-make-temp-file
277                (expand-file-name "mm" mm-tmp-directory))))
278     (let ((coding-system-for-write 'binary))
279       (write-region (point-min) (point-max) file nil 'silent))
280     (delete-region (point-min) (point-max))
281     (unwind-protect
282         (apply 'call-process cmd nil t nil (mapcar 'eval args))
283       (delete-file file))
284     (and post-func (funcall post-func))))
285
286 (defun mm-inline-wash-with-stdin (post-func cmd &rest args)
287   (let ((coding-system-for-write 'binary))
288     (apply 'call-process-region (point-min) (point-max)
289            cmd t t nil args))
290   (and post-func (funcall post-func)))
291
292 (defun mm-inline-render-with-file (handle post-func cmd &rest args)
293   (let ((source (mm-get-part handle)))
294     (mm-insert-inline
295      handle
296      (mm-with-unibyte-buffer
297        (insert source)
298        (apply 'mm-inline-wash-with-file post-func cmd args)
299        (buffer-string)))))
300
301 (defun mm-inline-render-with-stdin (handle post-func cmd &rest args)
302   (let ((source (mm-get-part handle)))
303     (mm-insert-inline
304      handle
305      (mm-with-unibyte-buffer
306        (insert source)
307        (apply 'mm-inline-wash-with-stdin post-func cmd args)
308        (buffer-string)))))
309
310 (defun mm-inline-render-with-function (handle func &rest args)
311   (let ((source (mm-get-part handle)))
312     (mm-insert-inline
313      handle
314      (mm-with-unibyte-buffer
315        (insert source)
316        (apply func args)
317        (buffer-string)))))
318
319 (defun mm-inline-text-html (handle)
320   (let* ((func (or mm-inline-text-html-renderer mm-text-html-renderer))
321          (entry (assq func mm-text-html-renderer-alist))
322          buffer-read-only)
323     (if entry
324         (setq func (cdr entry)))
325     (cond
326      ((gnus-functionp func)
327       (funcall func handle))
328      (t
329       (apply (car func) handle (cdr func))))))
330
331 (defun mm-inline-text-vcard (handle)
332   (let (buffer-read-only)
333     (mm-insert-inline
334      handle
335      (concat "\n-- \n"
336              (ignore-errors
337                (if (fboundp 'vcard-pretty-print)
338                    (vcard-pretty-print (mm-get-part handle))
339                  (vcard-format-string
340                   (vcard-parse-string (mm-get-part handle)
341                                       'vcard-standard-filter))))))))
342
343 (defun mm-inline-text (handle)
344   (let ((b (point))
345         (type (mm-handle-media-subtype handle))
346         (charset (mail-content-type-get
347                   (mm-handle-type handle) 'charset))
348         buffer-read-only)
349     (if (or (eq charset 'gnus-decoded)
350             ;; This is probably not entirely correct, but
351             ;; makes rfc822 parts with embedded multiparts work.
352             (eq mail-parse-charset 'gnus-decoded))
353         (save-restriction
354           (narrow-to-region (point) (point))
355           (mm-insert-part handle)
356           (goto-char (point-max)))
357       (insert (mm-decode-string (mm-get-part handle) charset)))
358     (when (and (equal type "plain")
359                (equal (cdr (assoc 'format (mm-handle-type handle)))
360                       "flowed"))
361       (save-restriction
362         (narrow-to-region b (point))
363         (goto-char b)
364         (fill-flowed)
365         (goto-char (point-max))))
366     (save-restriction
367       (narrow-to-region b (point))
368       (set-text-properties (point-min) (point-max) nil)
369       (when (or (equal type "enriched")
370                 (equal type "richtext"))
371         (enriched-decode (point-min) (point-max)))
372       (mm-handle-set-undisplayer
373        handle
374        `(lambda ()
375           (let (buffer-read-only)
376             (delete-region ,(point-min-marker)
377                            ,(point-max-marker))))))))
378
379 (defun mm-insert-inline (handle text)
380   "Insert TEXT inline from HANDLE."
381   (let ((b (point)))
382     (insert text)
383     (mm-handle-set-undisplayer
384      handle
385      `(lambda ()
386         (let (buffer-read-only)
387           (delete-region ,(set-marker (make-marker) b)
388                          ,(set-marker (make-marker) (point))))))))
389
390 (defun mm-inline-audio (handle)
391   (message "Not implemented"))
392
393 (defun mm-view-sound-file ()
394   (message "Not implemented"))
395
396 (defun mm-w3-prepare-buffer ()
397   (require 'w3)
398   (let ((url-standalone-mode t)
399         (url-gateway-unplugged t)
400         (w3-honor-stylesheets nil))
401     (w3-prepare-buffer)))
402
403 (defun mm-view-message ()
404   (mm-enable-multibyte)
405   (let (handles)
406     (let (gnus-article-mime-handles)
407       ;; Double decode problem may happen.  See mm-inline-message.
408       (run-hooks 'gnus-article-decode-hook)
409       (gnus-article-prepare-display)
410       (setq handles gnus-article-mime-handles))
411     (when handles
412       (setq gnus-article-mime-handles
413             (mm-merge-handles gnus-article-mime-handles handles))))
414   (fundamental-mode)
415   (goto-char (point-min)))
416
417 (defun mm-inline-message (handle)
418   (let ((b (point))
419         (bolp (bolp))
420         (charset (mail-content-type-get
421                   (mm-handle-type handle) 'charset))
422         gnus-displaying-mime handles)
423     (when (and charset
424                (stringp charset))
425       (setq charset (intern (downcase charset)))
426       (when (eq charset 'us-ascii)
427         (setq charset nil)))
428     (save-excursion
429       (save-restriction
430         (narrow-to-region b b)
431         (mm-insert-part handle)
432         (let (gnus-article-mime-handles
433               ;; disable prepare hook
434               gnus-article-prepare-hook
435               (gnus-newsgroup-charset
436                (or charset gnus-newsgroup-charset)))
437           (run-hooks 'gnus-article-decode-hook)
438           (gnus-article-prepare-display)
439           (setq handles gnus-article-mime-handles))
440         (goto-char (point-min))
441         (unless bolp
442           (insert "\n"))
443         (goto-char (point-max))
444         (unless (bolp)
445           (insert "\n"))
446         (insert "----------\n\n")
447         (when handles
448           (setq gnus-article-mime-handles
449                 (mm-merge-handles gnus-article-mime-handles handles)))
450         (mm-handle-set-undisplayer
451          handle
452          `(lambda ()
453             (let (buffer-read-only)
454               (if (fboundp 'remove-specifier)
455                   ;; This is only valid on XEmacs.
456                   (mapcar (lambda (prop)
457                             (remove-specifier
458                              (face-property 'default prop) (current-buffer)))
459                           '(background background-pixmap foreground)))
460               (delete-region ,(point-min-marker) ,(point-max-marker)))))))))
461
462 (defun mm-display-inline-fontify (handle mode)
463   (let (text)
464     ;; XEmacs @#$@ version of font-lock refuses to fully turn itself
465     ;; on for buffers whose name begins with " ".  That's why we use
466     ;; save-current-buffer/get-buffer-create rather than
467     ;; with-temp-buffer.
468     (save-current-buffer
469       (set-buffer (generate-new-buffer "*fontification*"))
470       (unwind-protect
471           (progn
472             (buffer-disable-undo)
473             (mm-insert-part handle)
474             (funcall mode)
475             (require 'font-lock)
476             (let ((font-lock-verbose nil))
477               ;; I find font-lock a bit too verbose.
478               (font-lock-fontify-buffer))
479             ;; By default, XEmacs font-lock uses non-duplicable text
480             ;; properties.  This code forces all the text properties
481             ;; to be copied along with the text.
482             (when (fboundp 'extent-list)
483               (map-extents (lambda (ext ignored)
484                              (set-extent-property ext 'duplicable t)
485                              nil)
486                            nil nil nil nil nil 'text-prop))
487             (setq text (buffer-string)))
488         (kill-buffer (current-buffer))))
489     (mm-insert-inline handle text)))
490
491 ;; Shouldn't these functions check whether the user even wants to use
492 ;; font-lock?  At least under XEmacs, this fontification is pretty
493 ;; much unconditional.  Also, it would be nice to change for the size
494 ;; of the fontified region.
495
496 (defun mm-display-patch-inline (handle)
497   (mm-display-inline-fontify handle 'diff-mode))
498
499 (defun mm-display-elisp-inline (handle)
500   (mm-display-inline-fontify handle 'emacs-lisp-mode))
501
502 ;;      id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
503 ;;          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }
504 (defvar mm-pkcs7-signed-magic
505   (mm-string-as-unibyte
506    (apply 'concat
507           (mapcar 'char-to-string
508                   (list ?\x30 ?\x5c ?\x28 ?\x80 ?\x5c ?\x7c ?\x81 ?\x2e ?\x5c
509                         ?\x7c ?\x82 ?\x2e ?\x2e ?\x5c ?\x7c ?\x83 ?\x2e ?\x2e
510                         ?\x2e ?\x5c ?\x29 ?\x06 ?\x09 ?\x5c ?\x2a ?\x86 ?\x48
511                         ?\x86 ?\xf7 ?\x0d ?\x01 ?\x07 ?\x02)))))
512
513 ;;      id-envelopedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
514 ;;          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 3 }
515 (defvar mm-pkcs7-enveloped-magic
516   (mm-string-as-unibyte
517    (apply 'concat
518           (mapcar 'char-to-string
519                   (list ?\x30 ?\x5c ?\x28 ?\x80 ?\x5c ?\x7c ?\x81 ?\x2e ?\x5c
520                         ?\x7c ?\x82 ?\x2e ?\x2e ?\x5c ?\x7c ?\x83 ?\x2e ?\x2e
521                         ?\x2e ?\x5c ?\x29 ?\x06 ?\x09 ?\x5c ?\x2a ?\x86 ?\x48
522                         ?\x86 ?\xf7 ?\x0d ?\x01 ?\x07 ?\x03)))))
523
524 (defun mm-view-pkcs7-get-type (handle)
525   (mm-with-unibyte-buffer
526     (mm-insert-part handle)
527     (cond ((looking-at mm-pkcs7-enveloped-magic)
528            'enveloped)
529           ((looking-at mm-pkcs7-signed-magic)
530            'signed)
531           (t
532            (error "Could not identify PKCS#7 type")))))
533
534 (defun mm-view-pkcs7 (handle)
535   (case (mm-view-pkcs7-get-type handle)
536     (enveloped (mm-view-pkcs7-decrypt handle))
537     (signed (mm-view-pkcs7-verify handle))
538     (otherwise (error "Unknown or unimplemented PKCS#7 type"))))
539
540 (defun mm-view-pkcs7-verify (handle)
541   ;; A bogus implementation of PKCS#7. FIXME::
542   (mm-insert-part handle)
543   (goto-char (point-min))
544   (if (search-forward "Content-Type: " nil t)
545       (delete-region (point-min) (match-beginning 0)))
546   (goto-char (point-max))
547   (if (re-search-backward "--\r?\n?" nil t)
548       (delete-region (match-end 0) (point-max)))
549   (goto-char (point-min))
550   (while (search-forward "\r\n" nil t)
551     (replace-match "\n"))
552   (message "Verify signed PKCS#7 message is unimplemented.")
553   (sit-for 1)
554   t)
555
556 (defun mm-view-pkcs7-decrypt (handle)
557   (insert-buffer (mm-handle-buffer handle))
558   (goto-char (point-min))
559   (insert "MIME-Version: 1.0\n")
560   (mm-insert-headers "application/pkcs7-mime" "base64" "smime.p7m")
561   (smime-decrypt-region
562    (point-min) (point-max)
563    (if (= (length smime-keys) 1)
564        (cadar smime-keys)
565      (smime-get-key-by-email
566       (completing-read
567        (concat "Decipher using which key? "
568                (if smime-keys (concat "(default " (caar smime-keys) ") ")
569                  ""))
570        smime-keys nil nil nil nil (car-safe (car-safe smime-keys))))))
571   (goto-char (point-min))
572   (while (search-forward "\r\n" nil t)
573     (replace-match "\n"))
574   (goto-char (point-min)))
575
576 (provide 'mm-view)
577
578 ;;; mm-view.el ends here