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