* mm-view.el (mm-inline-text): Ignore errors from enriched-decode.
[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   (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         (ignore-errors
373           (enriched-decode (point-min) (point-max))))
374       (mm-handle-set-undisplayer
375        handle
376        `(lambda ()
377           (let (buffer-read-only)
378             (delete-region ,(point-min-marker)
379                            ,(point-max-marker))))))))
380
381 (defun mm-insert-inline (handle text)
382   "Insert TEXT inline from HANDLE."
383   (let ((b (point)))
384     (insert text)
385     (mm-handle-set-undisplayer
386      handle
387      `(lambda ()
388         (let (buffer-read-only)
389           (delete-region ,(set-marker (make-marker) b)
390                          ,(set-marker (make-marker) (point))))))))
391
392 (defun mm-inline-audio (handle)
393   (message "Not implemented"))
394
395 (defun mm-view-sound-file ()
396   (message "Not implemented"))
397
398 (defun mm-w3-prepare-buffer ()
399   (require 'w3)
400   (let ((url-standalone-mode t)
401         (url-gateway-unplugged t)
402         (w3-honor-stylesheets nil))
403     (w3-prepare-buffer)))
404
405 (defun mm-view-message ()
406   (mm-enable-multibyte)
407   (let (handles)
408     (let (gnus-article-mime-handles)
409       ;; Double decode problem may happen.  See mm-inline-message.
410       (run-hooks 'gnus-article-decode-hook)
411       (gnus-article-prepare-display)
412       (setq handles gnus-article-mime-handles))
413     (when handles
414       (setq gnus-article-mime-handles
415             (mm-merge-handles gnus-article-mime-handles handles))))
416   (fundamental-mode)
417   (goto-char (point-min)))
418
419 (defun mm-inline-message (handle)
420   (let ((b (point))
421         (bolp (bolp))
422         (charset (mail-content-type-get
423                   (mm-handle-type handle) 'charset))
424         gnus-displaying-mime handles)
425     (when (and charset
426                (stringp charset))
427       (setq charset (intern (downcase charset)))
428       (when (eq charset 'us-ascii)
429         (setq charset nil)))
430     (save-excursion
431       (save-restriction
432         (narrow-to-region b b)
433         (mm-insert-part handle)
434         (let (gnus-article-mime-handles
435               ;; disable prepare hook
436               gnus-article-prepare-hook
437               (gnus-newsgroup-charset
438                (or charset gnus-newsgroup-charset)))
439           (run-hooks 'gnus-article-decode-hook)
440           (gnus-article-prepare-display)
441           (setq handles gnus-article-mime-handles))
442         (goto-char (point-min))
443         (unless bolp
444           (insert "\n"))
445         (goto-char (point-max))
446         (unless (bolp)
447           (insert "\n"))
448         (insert "----------\n\n")
449         (when handles
450           (setq gnus-article-mime-handles
451                 (mm-merge-handles gnus-article-mime-handles handles)))
452         (mm-handle-set-undisplayer
453          handle
454          `(lambda ()
455             (let (buffer-read-only)
456               (if (fboundp 'remove-specifier)
457                   ;; This is only valid on XEmacs.
458                   (mapcar (lambda (prop)
459                             (remove-specifier
460                              (face-property 'default prop) (current-buffer)))
461                           '(background background-pixmap foreground)))
462               (delete-region ,(point-min-marker) ,(point-max-marker)))))))))
463
464 (defun mm-display-inline-fontify (handle mode)
465   (let (text)
466     ;; XEmacs @#$@ version of font-lock refuses to fully turn itself
467     ;; on for buffers whose name begins with " ".  That's why we use
468     ;; save-current-buffer/get-buffer-create rather than
469     ;; with-temp-buffer.
470     (save-current-buffer
471       (set-buffer (generate-new-buffer "*fontification*"))
472       (unwind-protect
473           (progn
474             (buffer-disable-undo)
475             (mm-insert-part handle)
476             (funcall mode)
477             (require 'font-lock)
478             (let ((font-lock-verbose nil))
479               ;; I find font-lock a bit too verbose.
480               (font-lock-fontify-buffer))
481             ;; By default, XEmacs font-lock uses non-duplicable text
482             ;; properties.  This code forces all the text properties
483             ;; to be copied along with the text.
484             (when (fboundp 'extent-list)
485               (map-extents (lambda (ext ignored)
486                              (set-extent-property ext 'duplicable t)
487                              nil)
488                            nil nil nil nil nil 'text-prop))
489             (setq text (buffer-string)))
490         (kill-buffer (current-buffer))))
491     (mm-insert-inline handle text)))
492
493 ;; Shouldn't these functions check whether the user even wants to use
494 ;; font-lock?  At least under XEmacs, this fontification is pretty
495 ;; much unconditional.  Also, it would be nice to change for the size
496 ;; of the fontified region.
497
498 (defun mm-display-patch-inline (handle)
499   (mm-display-inline-fontify handle 'diff-mode))
500
501 (defun mm-display-elisp-inline (handle)
502   (mm-display-inline-fontify handle 'emacs-lisp-mode))
503
504 ;;      id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
505 ;;          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }
506 (defvar mm-pkcs7-signed-magic
507   (mm-string-as-unibyte
508    (apply 'concat
509           (mapcar 'char-to-string
510                   (list ?\x30 ?\x5c ?\x28 ?\x80 ?\x5c ?\x7c ?\x81 ?\x2e ?\x5c
511                         ?\x7c ?\x82 ?\x2e ?\x2e ?\x5c ?\x7c ?\x83 ?\x2e ?\x2e
512                         ?\x2e ?\x5c ?\x29 ?\x06 ?\x09 ?\x5c ?\x2a ?\x86 ?\x48
513                         ?\x86 ?\xf7 ?\x0d ?\x01 ?\x07 ?\x02)))))
514
515 ;;      id-envelopedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
516 ;;          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 3 }
517 (defvar mm-pkcs7-enveloped-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 ?\x03)))))
525
526 (defun mm-view-pkcs7-get-type (handle)
527   (mm-with-unibyte-buffer
528     (mm-insert-part handle)
529     (cond ((looking-at mm-pkcs7-enveloped-magic)
530            'enveloped)
531           ((looking-at mm-pkcs7-signed-magic)
532            'signed)
533           (t
534            (error "Could not identify PKCS#7 type")))))
535
536 (defun mm-view-pkcs7 (handle)
537   (case (mm-view-pkcs7-get-type handle)
538     (enveloped (mm-view-pkcs7-decrypt handle))
539     (signed (mm-view-pkcs7-verify handle))
540     (otherwise (error "Unknown or unimplemented PKCS#7 type"))))
541
542 (defun mm-view-pkcs7-verify (handle)
543   ;; A bogus implementation of PKCS#7. FIXME::
544   (mm-insert-part handle)
545   (goto-char (point-min))
546   (if (search-forward "Content-Type: " nil t)
547       (delete-region (point-min) (match-beginning 0)))
548   (goto-char (point-max))
549   (if (re-search-backward "--\r?\n?" nil t)
550       (delete-region (match-end 0) (point-max)))
551   (goto-char (point-min))
552   (while (search-forward "\r\n" nil t)
553     (replace-match "\n"))
554   (message "Verify signed PKCS#7 message is unimplemented.")
555   (sit-for 1)
556   t)
557
558 (defun mm-view-pkcs7-decrypt (handle)
559   (insert-buffer (mm-handle-buffer handle))
560   (goto-char (point-min))
561   (insert "MIME-Version: 1.0\n")
562   (mm-insert-headers "application/pkcs7-mime" "base64" "smime.p7m")
563   (smime-decrypt-region
564    (point-min) (point-max)
565    (if (= (length smime-keys) 1)
566        (cadar smime-keys)
567      (smime-get-key-by-email
568       (completing-read
569        (concat "Decipher using which key? "
570                (if smime-keys (concat "(default " (caar smime-keys) ") ")
571                  ""))
572        smime-keys nil nil nil nil (car-safe (car-safe smime-keys))))))
573   (goto-char (point-min))
574   (while (search-forward "\r\n" nil t)
575     (replace-match "\n"))
576   (goto-char (point-min)))
577
578 (provide 'mm-view)
579
580 ;;; mm-view.el ends here