(mm-inline-text): Withdraw the last change.
[gnus] / lisp / mm-view.el
1 ;;; mm-view.el --- functions for viewing MIME objects
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
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   (dolist (elem handle)
206     (when (listp elem)
207       (if (equal url (mm-handle-id elem))
208           (progn
209             (mm-insert-part elem)
210             (throw 'found-handle (mm-handle-media-type elem))))
211       (if (equal "multipart" (mm-handle-media-supertype elem))
212           (mm-w3m-cid-retrieve-1 url elem)))))
213
214 (defun mm-w3m-cid-retrieve (url &rest args)
215   "Insert a content pointed by URL if it has the cid: scheme."
216   (when (string-match "\\`cid:" url)
217     (catch 'found-handle
218       (mm-w3m-cid-retrieve-1 (concat "<" (substring url (match-end 0)) ">")
219                              (with-current-buffer w3m-current-buffer
220                                gnus-article-mime-handles)))))
221
222 (defun mm-inline-text-html-render-with-w3m (handle)
223   "Render a text/html part using emacs-w3m."
224   (mm-setup-w3m)
225   (let ((text (mm-get-part handle))
226         (b (point))
227         (charset (mail-content-type-get (mm-handle-type handle) 'charset)))
228     (save-excursion
229       (insert (if charset (mm-decode-string text charset) text))
230       (save-restriction
231         (narrow-to-region b (point))
232         (unless charset
233           (goto-char (point-min))
234           (when (setq charset (w3m-detect-meta-charset))
235             (delete-region (point-min) (point-max))
236             (insert (mm-decode-string text charset))))
237         (let ((w3m-safe-url-regexp mm-w3m-safe-url-regexp)
238               w3m-force-redisplay)
239           (w3m-region (point-min) (point-max) nil charset))
240         (when (and mm-inline-text-html-with-w3m-keymap
241                    (boundp 'w3m-minor-mode-map)
242                    w3m-minor-mode-map)
243           (add-text-properties
244            (point-min) (point-max)
245            (list 'keymap w3m-minor-mode-map
246                  ;; Put the mark meaning this part was rendered by emacs-w3m.
247                  'mm-inline-text-html-with-w3m t))))
248       (mm-handle-set-undisplayer
249        handle
250        `(lambda ()
251           (let (buffer-read-only)
252             (if (functionp 'remove-specifier)
253                 (mapcar (lambda (prop)
254                           (remove-specifier
255                            (face-property 'default prop)
256                            (current-buffer)))
257                         '(background background-pixmap foreground)))
258             (delete-region ,(point-min-marker)
259                            ,(point-max-marker))))))))
260
261 (defun mm-links-remove-leading-blank ()
262   ;; Delete the annoying three spaces preceding each line of links
263   ;; output.
264   (goto-char (point-min))
265   (while (re-search-forward "^   " nil t)
266     (delete-region (match-beginning 0) (match-end 0))))
267
268 (defun mm-inline-wash-with-file (post-func cmd &rest args)
269   (let ((file (mm-make-temp-file
270                (expand-file-name "mm" mm-tmp-directory))))
271     (let ((coding-system-for-write 'binary))
272       (write-region (point-min) (point-max) file nil 'silent))
273     (delete-region (point-min) (point-max))
274     (unwind-protect
275         (apply 'call-process cmd nil t nil (mapcar 'eval args))
276       (delete-file file))
277     (and post-func (funcall post-func))))
278
279 (defun mm-inline-wash-with-stdin (post-func cmd &rest args)
280   (let ((coding-system-for-write 'binary))
281     (apply 'call-process-region (point-min) (point-max)
282            cmd t t nil args))
283   (and post-func (funcall post-func)))
284
285 (defun mm-inline-render-with-file (handle post-func cmd &rest args)
286   (let ((source (mm-get-part handle)))
287     (mm-insert-inline
288      handle
289      (mm-with-unibyte-buffer
290        (insert source)
291        (apply 'mm-inline-wash-with-file post-func cmd args)
292        (buffer-string)))))
293
294 (defun mm-inline-render-with-stdin (handle post-func cmd &rest args)
295   (let ((source (mm-get-part handle)))
296     (mm-insert-inline
297      handle
298      (mm-with-unibyte-buffer
299        (insert source)
300        (apply 'mm-inline-wash-with-stdin post-func cmd args)
301        (buffer-string)))))
302
303 (defun mm-inline-render-with-function (handle func &rest args)
304   (let ((source (mm-get-part handle))
305         (charset (mail-content-type-get (mm-handle-type handle) 'charset)))
306     (mm-insert-inline
307      handle
308      (mm-with-multibyte-buffer
309        (insert (if charset
310                    (mm-decode-string source charset)
311                  source))
312        (apply func args)
313        (buffer-string)))))
314
315 (defun mm-inline-text-html (handle)
316   (let* ((func (or mm-inline-text-html-renderer mm-text-html-renderer))
317          (entry (assq func mm-text-html-renderer-alist))
318          buffer-read-only)
319     (if entry
320         (setq func (cdr entry)))
321     (cond
322      ((functionp func)
323       (funcall func handle))
324      (t
325       (apply (car func) handle (cdr func))))))
326
327 (defun mm-inline-text-vcard (handle)
328   (let (buffer-read-only)
329     (mm-insert-inline
330      handle
331      (concat "\n-- \n"
332              (ignore-errors
333                (if (fboundp 'vcard-pretty-print)
334                    (vcard-pretty-print (mm-get-part handle))
335                  (vcard-format-string
336                   (vcard-parse-string (mm-get-part handle)
337                                       'vcard-standard-filter))))))))
338
339 (defun mm-inline-text (handle)
340   (let ((b (point))
341         (type (mm-handle-media-subtype handle))
342         (charset (mail-content-type-get
343                   (mm-handle-type handle) 'charset))
344         buffer-read-only)
345     (if (or (eq charset 'gnus-decoded)
346             ;; This is probably not entirely correct, but
347             ;; makes rfc822 parts with embedded multiparts work.
348             (eq mail-parse-charset 'gnus-decoded))
349         (save-restriction
350           (narrow-to-region (point) (point))
351           (mm-insert-part handle)
352           (goto-char (point-max)))
353       (insert (mm-decode-string (mm-get-part handle) charset)))
354     (when (and mm-fill-flowed
355                (equal type "plain")
356                (equal (cdr (assoc 'format (mm-handle-type handle)))
357                       "flowed"))
358       (save-restriction
359         (narrow-to-region b (point))
360         (goto-char b)
361         (fill-flowed)
362         (goto-char (point-max))))
363     (save-restriction
364       (narrow-to-region b (point))
365       (set-text-properties (point-min) (point-max) nil)
366       (when (or (equal type "enriched")
367                 (equal type "richtext"))
368         (ignore-errors
369           (enriched-decode (point-min) (point-max))))
370       (mm-handle-set-undisplayer
371        handle
372        `(lambda ()
373           (let (buffer-read-only)
374             (delete-region ,(point-min-marker)
375                            ,(point-max-marker))))))))
376
377 (defun mm-insert-inline (handle text)
378   "Insert TEXT inline from HANDLE."
379   (let ((b (point)))
380     (insert text)
381     (unless (bolp)
382       (insert "\n"))
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           (let ((gnus-original-article-buffer (mm-handle-buffer handle)))
438             (run-hooks 'gnus-article-decode-hook))
439           (gnus-article-prepare-display)
440           (setq handles gnus-article-mime-handles))
441         (goto-char (point-min))
442         (unless bolp
443           (insert "\n"))
444         (goto-char (point-max))
445         (unless (bolp)
446           (insert "\n"))
447         (insert "----------\n\n")
448         (when handles
449           (setq gnus-article-mime-handles
450                 (mm-merge-handles gnus-article-mime-handles handles)))
451         (mm-handle-set-undisplayer
452          handle
453          `(lambda ()
454             (let (buffer-read-only)
455               (if (fboundp 'remove-specifier)
456                   ;; This is only valid on XEmacs.
457                   (mapcar (lambda (prop)
458                             (remove-specifier
459                              (face-property 'default prop) (current-buffer)))
460                           '(background background-pixmap foreground)))
461               (delete-region ,(point-min-marker) ,(point-max-marker)))))))))
462
463 (defun mm-display-inline-fontify (handle mode)
464   (let ((charset (mail-content-type-get (mm-handle-type handle) 'charset))
465         text coding-system)
466     (unless (eq charset 'gnus-decoded)
467       (mm-with-unibyte-buffer
468         (mm-insert-part handle)
469         (mm-decompress-buffer
470          (or (mail-content-type-get (mm-handle-disposition handle) 'name)
471              (mail-content-type-get (mm-handle-disposition handle) 'filename))
472          t t)
473         (unless charset
474           (setq coding-system (mm-find-buffer-file-coding-system)))
475         (setq text (buffer-string))))
476     ;; XEmacs @#$@ version of font-lock refuses to fully turn itself
477     ;; on for buffers whose name begins with " ".  That's why we use
478     ;; `with-current-buffer'/`generate-new-buffer' rather than
479     ;; `with-temp-buffer'.
480     (with-current-buffer (generate-new-buffer "*fontification*")
481       (buffer-disable-undo)
482       (mm-enable-multibyte)
483       (insert (cond ((eq charset 'gnus-decoded)
484                      (mm-insert-part handle))
485                     (coding-system
486                      (mm-decode-coding-string text coding-system))
487                     (charset
488                      (mm-decode-string text charset))
489                     (t
490                      text)))
491       (require 'font-lock)
492       ;; Inhibit font-lock this time (*-mode-hook might run
493       ;; `turn-on-font-lock') so that jit-lock may not turn off
494       ;; font-lock immediately after this.
495       (let ((font-lock-mode t))
496         (funcall mode))
497       (let ((font-lock-verbose nil))
498         ;; I find font-lock a bit too verbose.
499         (font-lock-fontify-buffer))
500       ;; By default, XEmacs font-lock uses non-duplicable text
501       ;; properties.  This code forces all the text properties
502       ;; to be copied along with the text.
503       (when (fboundp 'extent-list)
504         (map-extents (lambda (ext ignored)
505                        (set-extent-property ext 'duplicable t)
506                        nil)
507                      nil nil nil nil nil 'text-prop))
508       (setq text (buffer-string))
509       (kill-buffer (current-buffer)))
510     (mm-insert-inline handle text)))
511
512 ;; Shouldn't these functions check whether the user even wants to use
513 ;; font-lock?  At least under XEmacs, this fontification is pretty
514 ;; much unconditional.  Also, it would be nice to change for the size
515 ;; of the fontified region.
516
517 (defun mm-display-patch-inline (handle)
518   (mm-display-inline-fontify handle 'diff-mode))
519
520 (defun mm-display-elisp-inline (handle)
521   (mm-display-inline-fontify handle 'emacs-lisp-mode))
522
523 (defun mm-display-dns-inline (handle)
524   (mm-display-inline-fontify handle 'dns-mode))
525
526 ;;      id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
527 ;;          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }
528 (defvar mm-pkcs7-signed-magic
529   (mm-string-as-unibyte
530    (mapconcat 'char-to-string
531               (list ?\x30 ?\x5c ?\x28 ?\x80 ?\x5c ?\x7c ?\x81 ?\x2e ?\x5c
532                     ?\x7c ?\x82 ?\x2e ?\x2e ?\x5c ?\x7c ?\x83 ?\x2e ?\x2e
533                     ?\x2e ?\x5c ?\x29 ?\x06 ?\x09 ?\x5c ?\x2a ?\x86 ?\x48
534                     ?\x86 ?\xf7 ?\x0d ?\x01 ?\x07 ?\x02) "")))
535
536 ;;      id-envelopedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
537 ;;          us(840) rsadsi(113549) pkcs(1) pkcs7(7) 3 }
538 (defvar mm-pkcs7-enveloped-magic
539   (mm-string-as-unibyte
540    (mapconcat 'char-to-string
541               (list ?\x30 ?\x5c ?\x28 ?\x80 ?\x5c ?\x7c ?\x81 ?\x2e ?\x5c
542                     ?\x7c ?\x82 ?\x2e ?\x2e ?\x5c ?\x7c ?\x83 ?\x2e ?\x2e
543                     ?\x2e ?\x5c ?\x29 ?\x06 ?\x09 ?\x5c ?\x2a ?\x86 ?\x48
544                     ?\x86 ?\xf7 ?\x0d ?\x01 ?\x07 ?\x03) "")))
545
546 (defun mm-view-pkcs7-get-type (handle)
547   (mm-with-unibyte-buffer
548     (mm-insert-part handle)
549     (cond ((looking-at mm-pkcs7-enveloped-magic)
550            'enveloped)
551           ((looking-at mm-pkcs7-signed-magic)
552            'signed)
553           (t
554            (error "Could not identify PKCS#7 type")))))
555
556 (defun mm-view-pkcs7 (handle)
557   (case (mm-view-pkcs7-get-type handle)
558     (enveloped (mm-view-pkcs7-decrypt handle))
559     (signed (mm-view-pkcs7-verify handle))
560     (otherwise (error "Unknown or unimplemented PKCS#7 type"))))
561
562 (defun mm-view-pkcs7-verify (handle)
563   ;; A bogus implementation of PKCS#7. FIXME::
564   (mm-insert-part handle)
565   (goto-char (point-min))
566   (if (search-forward "Content-Type: " nil t)
567       (delete-region (point-min) (match-beginning 0)))
568   (goto-char (point-max))
569   (if (re-search-backward "--\r?\n?" nil t)
570       (delete-region (match-end 0) (point-max)))
571   (goto-char (point-min))
572   (while (search-forward "\r\n" nil t)
573     (replace-match "\n"))
574   (message "Verify signed PKCS#7 message is unimplemented.")
575   (sit-for 1)
576   t)
577
578 (defun mm-view-pkcs7-decrypt (handle)
579   (insert-buffer-substring (mm-handle-buffer handle))
580   (goto-char (point-min))
581   (insert "MIME-Version: 1.0\n")
582   (mm-insert-headers "application/pkcs7-mime" "base64" "smime.p7m")
583   (smime-decrypt-region
584    (point-min) (point-max)
585    (if (= (length smime-keys) 1)
586        (cadar smime-keys)
587      (smime-get-key-by-email
588       (completing-read
589        (concat "Decipher using which key? "
590                (if smime-keys (concat "(default " (caar smime-keys) ") ")
591                  ""))
592        smime-keys nil nil nil nil (car-safe (car-safe smime-keys))))))
593   (goto-char (point-min))
594   (while (search-forward "\r\n" nil t)
595     (replace-match "\n"))
596   (goto-char (point-min)))
597
598 (provide 'mm-view)
599
600 ;;; arch-tag: b60e749a-d05c-47f2-bccd-bdaa59327cb2
601 ;;; mm-view.el ends here