7ff14336bb3ba8ccdc15ca84e6ee2bab3aa665d2
[gnus] / lisp / mm-decode.el
1 ;;; mm-decode.el --- Functions for decoding MIME things
2 ;; Copyright (C) 1998,99 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
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 (require 'mail-parse)
28 (require 'mailcap)
29 (require 'mm-bodies)
30
31 ;;; Convenience macros.
32
33 (defmacro mm-handle-buffer (handle)
34   `(nth 0 ,handle))
35 (defmacro mm-handle-type (handle)
36   `(nth 1 ,handle))
37 (defmacro mm-handle-encoding (handle)
38   `(nth 2 ,handle))
39 (defmacro mm-handle-undisplayer (handle)
40   `(nth 3 ,handle))
41 (defmacro mm-handle-set-undisplayer (handle function)
42   `(setcar (nthcdr 3 ,handle) ,function))
43 (defmacro mm-handle-disposition (handle)
44   `(nth 4 ,handle))
45 (defmacro mm-handle-description (handle)
46   `(nth 5 ,handle))
47 (defmacro mm-handle-cache (handle)
48   `(nth 6 ,handle))
49 (defmacro mm-handle-set-cache (handle contents)
50   `(setcar (nthcdr 6 ,handle) ,contents))
51 (defmacro mm-handle-id (handle)
52   `(nth 7 ,handle))
53 (defmacro mm-make-handle (&optional buffer type encoding undisplayer
54                                     disposition description cache
55                                     id)
56   `(list ,buffer ,type ,encoding ,undisplayer
57          ,disposition ,description ,cache ,id))
58
59 (defvar mm-inline-media-tests
60   '(("image/jpeg" mm-inline-image
61      (and window-system (featurep 'jpeg) (mm-image-fit-p handle)))
62     ("image/png" mm-inline-image
63      (and window-system (featurep 'png) (mm-image-fit-p handle)))
64     ("image/gif" mm-inline-image
65      (and window-system (featurep 'gif) (mm-image-fit-p handle)))
66     ("image/tiff" mm-inline-image
67      (and window-system (featurep 'tiff) (mm-image-fit-p handle)))
68     ("image/xbm" mm-inline-image
69      (and window-system (fboundp 'device-type)
70           (eq (device-type) 'x)))
71     ("image/x-xbitmap" mm-inline-image
72      (and window-system (fboundp 'device-type)
73           (eq (device-type) 'x)))
74     ("image/xpm" mm-inline-image
75      (and window-system (featurep 'xpm)))
76     ("image/x-pixmap" mm-inline-image
77      (and window-system (featurep 'xpm)))
78     ("image/bmp" mm-inline-image
79      (and window-system (featurep 'bmp)))
80     ("text/plain" mm-inline-text t)
81     ("text/enriched" mm-inline-text t)
82     ("text/richtext" mm-inline-text t)
83     ("text/html" mm-inline-text (locate-library "w3"))
84     ("text/x-vcard" mm-inline-text (locate-library "vcard"))
85     ("message/delivery-status" mm-inline-text t)
86     ("text/.*" mm-inline-text t)
87     ("audio/wav" mm-inline-audio
88      (and (or (featurep 'nas-sound) (featurep 'native-sound))
89           (device-sound-enabled-p)))
90     ("audio/au" mm-inline-audio
91      (and (or (featurep 'nas-sound) (featurep 'native-sound))
92           (device-sound-enabled-p)))
93     ("multipart/alternative" ignore t)
94     ("multipart/mixed" ignore t)
95     ("multipart/related" ignore t))
96   "Alist of media types/test that say whether the media types can be displayed inline.")
97
98 (defvar mm-user-display-methods
99   '(("image/.*" . inline)
100     ("text/.*" . inline)
101     ("message/delivery-status" . inline)))
102
103 (defvar mm-user-automatic-display
104   '("text/plain" "text/enriched" "text/richtext" "text/html"
105     "text/x-vcard" "image/.*" "message/delivery-status" "multipart/.*"))
106
107 (defvar mm-attachment-override-types
108   '("text/plain" "text/x-vcard")
109   "Types that should have \"attachment\" ignored if they can be displayed inline.")
110
111 (defvar mm-user-automatic-external-display nil
112   "List of MIME type regexps that will be displayed externally automatically.")
113
114 (defvar mm-alternative-precedence
115   '("multipart/related" "multipart/mixed" "multipart/alternative"
116     "image/jpeg" "image/gif" "text/html" "text/enriched"
117     "text/richtext" "text/plain")
118   "List that describes the precedence of alternative parts.")
119
120 (defvar mm-tmp-directory
121   (cond ((fboundp 'temp-directory) (temp-directory))
122         ((boundp 'temporary-file-directory) temporary-file-directory)
123         ("/tmp/"))
124   "Where mm will store its temporary files.")
125
126 (defvar mm-all-images-fit nil
127   "If non-nil, then all images fit in the buffer.")
128
129 ;;; Internal variables.
130
131 (defvar mm-dissection-list nil)
132 (defvar mm-last-shell-command "")
133 (defvar mm-content-id-alist nil)
134
135 ;;; The functions.
136
137 (defun mm-dissect-buffer (&optional no-strict-mime)
138   "Dissect the current buffer and return a list of MIME handles."
139   (save-excursion
140     (let (ct ctl type subtype cte cd description id result)
141       (save-restriction
142         (mail-narrow-to-head)
143         (when (or no-strict-mime
144                   (mail-fetch-field "mime-version"))
145           (setq ct (mail-fetch-field "content-type")
146                 ctl (condition-case () (mail-header-parse-content-type ct)
147                       (error nil))
148                 cte (mail-fetch-field "content-transfer-encoding")
149                 cd (mail-fetch-field "content-disposition")
150                 description (mail-fetch-field "content-description")
151                 id (mail-fetch-field "content-id"))))
152       (if (or (not ctl)
153               (not (string-match "/" (car ctl))))
154           (mm-dissect-singlepart
155            '("text/plain") nil no-strict-mime
156            (and cd (condition-case ()
157                        (mail-header-parse-content-disposition cd)
158                      (error nil)))
159            description)
160         (setq type (split-string (car ctl) "/"))
161         (setq subtype (cadr type)
162               type (pop type))
163         (setq
164          result
165          (cond
166           ((equal type "multipart")
167            (cons (car ctl) (mm-dissect-multipart ctl)))
168           (t
169            (mm-dissect-singlepart
170             ctl
171             (and cte (intern (downcase (mail-header-remove-whitespace
172                                         (mail-header-remove-comments
173                                          cte)))))
174             no-strict-mime
175             (and cd (condition-case ()
176                         (mail-header-parse-content-disposition cd)
177                       (error nil)))
178             description id))))
179         (when id
180           (when (string-match " *<\\(.*\\)> *" id)
181             (setq id (match-string 1 id)))
182           (push (cons id result) mm-content-id-alist))
183         result))))
184
185 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
186   (when (or force
187             (not (equal "text/plain" (car ctl))))
188     (let ((res (mm-make-handle
189                 (mm-copy-to-buffer) ctl cte nil cdl description nil id)))
190       (push (car res) mm-dissection-list)
191       res)))
192
193 (defun mm-remove-all-parts ()
194   "Remove all MIME handles."
195   (interactive)
196   (mapcar 'mm-remove-part mm-dissection-list)
197   (setq mm-dissection-list nil))
198
199 (defun mm-dissect-multipart (ctl)
200   (goto-char (point-min))
201   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
202         (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
203         start parts
204         (end (save-excursion
205                (goto-char (point-max))
206                (if (re-search-backward close-delimiter nil t)
207                    (match-beginning 0)
208                  (point-max)))))
209     (while (search-forward boundary end t)
210       (goto-char (match-beginning 0))
211       (when start
212         (save-excursion
213           (save-restriction
214             (narrow-to-region start (point))
215             (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
216       (forward-line 2)
217       (setq start (point)))
218     (when start
219       (save-excursion
220         (save-restriction
221           (narrow-to-region start end)
222           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
223     (nreverse parts)))
224
225 (defun mm-copy-to-buffer ()
226   "Copy the contents of the current buffer to a fresh buffer."
227   (save-excursion
228     (let ((obuf (current-buffer))
229           beg)
230       (goto-char (point-min))
231       (search-forward-regexp "^\n" nil t)
232       (setq beg (point))
233       (set-buffer (generate-new-buffer " *mm*"))
234       (insert-buffer-substring obuf beg)
235       (current-buffer))))
236
237 (defun mm-inlinable-part-p (type)
238   "Say whether TYPE can be displayed inline."
239   (eq (mm-user-method type) 'inline))
240
241 (defun mm-display-part (handle &optional no-default)
242   "Display the MIME part represented by HANDLE.
243 Returns nil if the part is removed; inline if displayed inline;
244 external if displayed external."
245   (save-excursion
246     (mailcap-parse-mailcaps)
247     (if (mm-handle-displayed-p handle)
248         (mm-remove-part handle)
249       (let* ((type (car (mm-handle-type handle)))
250              (method (mailcap-mime-info type))
251              (user-method (mm-user-method type)))
252         (if (eq user-method 'inline)
253             (progn
254               (forward-line 1)
255               (mm-display-inline handle)
256               'inline)
257           (when (or user-method
258                     method
259                     (not no-default))
260             (if (and (not user-method)
261                      (not method)
262                      (equal "text" (car (split-string type))))
263                 (progn
264                   (forward-line 1)
265                   (mm-insert-inline handle (mm-get-part handle))
266                   'inline)
267               (mm-display-external
268                handle (or user-method method
269                           'mailcap-save-binary-file))
270               'external)))))))
271
272 (defun mm-display-external (handle method)
273   "Display HANDLE using METHOD."
274   (mm-with-unibyte-buffer
275     (if (functionp method)
276         (let ((cur (current-buffer)))
277           (if (eq method 'mailcap-save-binary-file)
278               (progn
279                 (set-buffer (generate-new-buffer "*mm*"))
280                 (setq method nil))
281             (mm-insert-part handle)
282             (let ((win (get-buffer-window cur t)))
283               (when win
284                 (select-window win)))
285             (switch-to-buffer (generate-new-buffer "*mm*")))
286           (buffer-disable-undo)
287           (mm-set-buffer-file-coding-system mm-binary-coding-system)
288           (insert-buffer-substring cur)
289           (message "Viewing with %s" method)
290           (let ((mm (current-buffer))
291                 (non-viewer (assoc "non-viewer"
292                                    (mailcap-mime-info
293                                     (car (mm-handle-type handle)) t))))
294             (unwind-protect
295                 (if method
296                     (funcall method)
297                   (mm-save-part handle))
298               (when (and (not non-viewer)
299                          method)
300                 (mm-handle-set-undisplayer handle mm)))))
301       ;; The function is a string to be executed.
302       (mm-insert-part handle)
303       (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
304              (filename (mail-content-type-get
305                         (mm-handle-disposition handle) 'filename))
306              (needsterm (assoc "needsterm"
307                                (mailcap-mime-info
308                                 (car (mm-handle-type handle)) t)))
309              process file buffer)
310         ;; We create a private sub-directory where we store our files.
311         (make-directory dir)
312         (set-file-modes dir 448)
313         (if filename
314             (setq file (expand-file-name (file-name-nondirectory filename)
315                                          dir))
316           (setq file (make-temp-name (expand-file-name "mm." dir))))
317         (write-region (point-min) (point-max) file nil 'nomesg)
318         (message "Viewing with %s" method)
319         (unwind-protect
320             (setq process
321                   (if needsterm
322                       (start-process "*display*" nil
323                                      "xterm"
324                                      "-e" shell-file-name "-c"
325                                      (format method
326                                              (mm-quote-arg file)))
327                     (start-process "*display*"
328                                    (setq buffer (generate-new-buffer "*mm*"))
329                                    shell-file-name
330                                    "-c" (format method
331                                                 (mm-quote-arg file)))))
332           (mm-handle-set-undisplayer handle (cons file buffer)))
333         (message "Displaying %s..." (format method file))))))
334
335 (defun mm-remove-parts (handles)
336   "Remove the displayed MIME parts represented by HANDLE."
337   (if (and (listp handles)
338            (bufferp (car handles)))
339       (mm-remove-part handles)
340     (let (handle)
341       (while (setq handle (pop handles))
342         (cond
343          ((stringp handle)
344           )
345          ((and (listp handle)
346                (stringp (car handle)))
347           (mm-remove-parts (cdr handle)))
348          (t
349           (mm-remove-part handle)))))))
350
351 (defun mm-destroy-parts (handles)
352   "Remove the displayed MIME parts represented by HANDLE."
353   (if (and (listp handles)
354            (bufferp (car handles)))
355       (mm-destroy-part handles)
356     (let (handle)
357       (while (setq handle (pop handles))
358         (cond
359          ((stringp handle)
360           )
361          ((and (listp handle)
362                (stringp (car handle)))
363           (mm-destroy-parts (cdr handle)))
364          (t
365           (mm-destroy-part handle)))))))
366
367 (defun mm-remove-part (handle)
368   "Remove the displayed MIME part represented by HANDLE."
369   (when (listp handle)
370     (let ((object (mm-handle-undisplayer handle)))
371       (condition-case ()
372           (cond
373            ;; Internally displayed part.
374            ((mm-annotationp object)
375             (delete-annotation object))
376            ((or (functionp object)
377                 (and (listp object)
378                      (eq (car object) 'lambda)))
379             (funcall object))
380            ;; Externally displayed part.
381            ((consp object)
382             (condition-case ()
383                 (delete-file (car object))
384               (error nil))
385             (condition-case ()
386                 (delete-directory (file-name-directory (car object)))
387               (error nil))
388             (condition-case ()
389                 (kill-buffer (cdr object))
390               (error nil)))
391            ((bufferp object)
392             (when (buffer-live-p object)
393               (kill-buffer object))))
394         (error nil))
395       (mm-handle-set-undisplayer handle nil))))
396
397 (defun mm-display-inline (handle)
398   (let* ((type (car (mm-handle-type handle)))
399          (function (cadr (assoc type mm-inline-media-tests))))
400     (funcall function handle)
401     (goto-char (point-min))))
402
403 (defun mm-inlinable-p (type)
404   "Say whether TYPE can be displayed inline."
405   (let ((alist mm-inline-media-tests)
406         test)
407     (while alist
408       (when (equal type (caar alist))
409         (setq test (caddar alist)
410               alist nil)
411         (setq test (eval test)))
412       (pop alist))
413     test))
414
415 (defun mm-user-method (type)
416   "Return the user-defined method for TYPE."
417   (let ((methods mm-user-display-methods)
418         method result)
419     (while (setq method (pop methods))
420       (when (string-match (car method) type)
421         (when (or (not (eq (cdr method) 'inline))
422                   (mm-inlinable-p type))
423           (setq result (cdr method)
424                 methods nil))))
425     result))
426
427 (defun mm-automatic-display-p (type)
428   "Return the user-defined method for TYPE."
429   (let ((methods mm-user-automatic-display)
430         method result)
431     (while (setq method (pop methods))
432       (when (and (string-match method type)
433                  (mm-inlinable-p type))
434         (setq result t
435               methods nil)))
436     result))
437
438 (defun mm-attachment-override-p (type)
439   "Say whether TYPE should have attachment behavior overridden."
440   (let ((types mm-attachment-override-types)
441         ty)
442     (catch 'found
443       (while (setq ty (pop types))
444         (when (and (string-match ty type)
445                    (mm-inlinable-p type))
446           (throw 'found t))))))
447
448 (defun mm-automatic-external-display-p (type)
449   "Return the user-defined method for TYPE."
450   (let ((methods mm-user-automatic-external-display)
451         method result)
452     (while (setq method (pop methods))
453       (when (string-match method type)
454         (setq result t
455               methods nil)))
456     result))
457
458 (defun add-mime-display-method (type method)
459   "Make parts of TYPE be displayed with METHOD.
460 This overrides entries in the mailcap file."
461   (push (cons type method) mm-user-display-methods))
462
463 (defun mm-destroy-part (handle)
464   "Destroy the data structures connected to HANDLE."
465   (when (listp handle)
466     (mm-remove-part handle)
467     (when (buffer-live-p (mm-handle-buffer handle))
468       (kill-buffer (mm-handle-buffer handle)))))
469
470 (defun mm-handle-displayed-p (handle)
471   "Say whether HANDLE is displayed or not."
472   (mm-handle-undisplayer handle))
473
474 (defun mm-quote-arg (arg)
475   "Return a version of ARG that is safe to evaluate in a shell."
476   (let ((pos 0) new-pos accum)
477     ;; *** bug: we don't handle newline characters properly
478     (while (setq new-pos (string-match "[;!`\"$\\& \t{} |()<>]" arg pos))
479       (push (substring arg pos new-pos) accum)
480       (push "\\" accum)
481       (push (list (aref arg new-pos)) accum)
482       (setq pos (1+ new-pos)))
483     (if (= pos 0)
484         arg
485       (apply 'concat (nconc (nreverse accum) (list (substring arg pos)))))))
486
487 ;;;
488 ;;; Functions for outputting parts
489 ;;;
490
491 (defun mm-get-part (handle)
492   "Return the contents of HANDLE as a string."
493   (mm-with-unibyte-buffer
494     (mm-insert-part handle)
495     (buffer-string)))
496
497 (defun mm-insert-part (handle)
498   "Insert the contents of HANDLE in the current buffer."
499   (let ((cur (current-buffer)))
500     (save-excursion
501       (mm-with-unibyte-buffer
502         (insert-buffer-substring (mm-handle-buffer handle))
503         (mm-decode-content-transfer-encoding
504          (mm-handle-encoding handle)
505          (car (mm-handle-type handle)))
506         (let ((temp (current-buffer)))
507           (set-buffer cur)
508           (insert-buffer-substring temp))))))
509
510 (defvar mm-default-directory nil)
511
512 (defun mm-save-part (handle)
513   "Write HANDLE to a file."
514   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
515          (filename (mail-content-type-get
516                     (mm-handle-disposition handle) 'filename))
517          file)
518     (when filename
519       (setq filename (file-name-nondirectory filename)))
520     (setq file
521           (read-file-name "Save MIME part to: "
522                           (expand-file-name
523                            (or filename name "")
524                            (or mm-default-directory default-directory))))
525     (setq mm-default-directory (file-name-directory file))
526     (mm-with-unibyte-buffer
527       (mm-insert-part handle)
528       (when (or (not (file-exists-p file))
529                 (yes-or-no-p (format "File %s already exists; overwrite? "
530                                      file)))
531         ;; Now every coding system is 100% binary within mm-with-unibyte-buffer
532         ;; Is text still special?
533       (let ((coding-system-for-write
534              (if (equal "text" (car (split-string
535                                      (car (mm-handle-type handle)) "/")))
536                  buffer-file-coding-system
537                'binary))
538             ;; Don't re-compress .gz & al.  Arguably we should make
539             ;; `file-name-handler-alist' nil, but that would chop
540             ;; ange-ftp which it's reasonable to use here.
541             (inhibit-file-name-operation 'write-region)
542             (inhibit-file-name-handlers
543              (if (equal (car (mm-handle-type handle))
544                         "application/octet-stream")
545                  (cons 'jka-compr-handler inhibit-file-name-handlers)
546                inhibit-file-name-handlers)))
547         (write-region (point-min) (point-max) file))))))
548
549 (defun mm-pipe-part (handle)
550   "Pipe HANDLE to a process."
551   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
552          (command
553           (read-string "Shell command on MIME part: " mm-last-shell-command)))
554     (mm-with-unibyte-buffer
555       (mm-insert-part handle)
556       (shell-command-on-region (point-min) (point-max) command nil))))
557
558 (defun mm-interactively-view-part (handle)
559   "Display HANDLE using METHOD."
560   (let* ((type (car (mm-handle-type handle)))
561          (methods
562           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
563                   (mailcap-mime-info type 'all)))
564          (method (completing-read "Viewer: " methods)))
565     (mm-display-external (copy-sequence handle) method)))
566
567 (defun mm-preferred-alternative (handles &optional preferred)
568   "Say which of HANDLES are preferred."
569   (let ((prec (if preferred (list preferred) mm-alternative-precedence))
570         p h result type handle)
571     (while (setq p (pop prec))
572       (setq h handles)
573       (while h
574         (setq type
575               (if (stringp (caar h))
576                   (caar h)
577                 (car (mm-handle-type (car h)))))
578         (setq handle (car h))
579         (when (and (equal p type)
580                    (mm-automatic-display-p type)
581                    (or (stringp (caar h))
582                        (not (mm-handle-disposition (car h)))
583                        (equal (car (mm-handle-disposition (car h)))
584                               "inline")))
585           (setq result (car h)
586                 h nil
587                 prec nil))
588         (pop h)))
589     result))
590
591 (defun mm-get-content-id (id)
592   "Return the handle(s) referred to by ID."
593   (cdr (assoc id mm-content-id-alist)))
594
595 (defun mm-get-image (handle)
596   "Return an image instance based on HANDLE."
597   (let ((type (cadr (split-string (car (mm-handle-type handle)) "/")))
598         spec)
599     ;; Allow some common translations.
600     (setq type
601           (cond
602            ((equal type "x-pixmap")
603             "xpm")
604            ((equal type "x-xbitmap")
605             "xbm")
606            (t type)))
607     (or (mm-handle-cache handle)
608         (mm-with-unibyte-buffer
609           (mm-insert-part handle)
610           (prog1
611               (setq spec
612                     (make-glyph `[,(intern type) :data ,(buffer-string)]))
613             (mm-handle-set-cache handle spec))))))
614
615 (defun mm-image-fit-p (handle)
616   "Say whether the image in HANDLE will fit the current window."
617   (let ((image (mm-get-image handle)))
618     (or mm-all-images-fit
619         (and (< (glyph-width image) (window-pixel-width))
620              (< (glyph-height image) (window-pixel-height))))))
621
622 (provide 'mm-decode)
623
624 ;; mm-decode.el ends here