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