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