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