c6983d7780ad87426bd8f2edbdd41059e97fe246
[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 (defgroup mime-display ()
32   "Display of MIME in mail and news articles."
33   :link '(custom-manual "(emacs-mime)Customization")
34   :group 'mail
35   :group 'news)
36
37 ;;; Convenience macros.
38
39 (defmacro mm-handle-buffer (handle)
40   `(nth 0 ,handle))
41 (defmacro mm-handle-type (handle)
42   `(nth 1 ,handle))
43 (defsubst mm-handle-media-type (handle)
44   (if (stringp (car handle))
45       (car handle)
46     (car (mm-handle-type handle))))
47 (defsubst mm-handle-media-supertype (handle)
48   (car (split-string (mm-handle-media-type handle) "/")))
49 (defsubst mm-handle-media-subtype (handle)
50   (cadr (split-string (mm-handle-media-type handle) "/")))
51 (defmacro mm-handle-encoding (handle)
52   `(nth 2 ,handle))
53 (defmacro mm-handle-undisplayer (handle)
54   `(nth 3 ,handle))
55 (defmacro mm-handle-set-undisplayer (handle function)
56   `(setcar (nthcdr 3 ,handle) ,function))
57 (defmacro mm-handle-disposition (handle)
58   `(nth 4 ,handle))
59 (defmacro mm-handle-description (handle)
60   `(nth 5 ,handle))
61 (defmacro mm-handle-cache (handle)
62   `(nth 6 ,handle))
63 (defmacro mm-handle-set-cache (handle contents)
64   `(setcar (nthcdr 6 ,handle) ,contents))
65 (defmacro mm-handle-id (handle)
66   `(nth 7 ,handle))
67 (defmacro mm-make-handle (&optional buffer type encoding undisplayer
68                                     disposition description cache
69                                     id)
70   `(list ,buffer ,type ,encoding ,undisplayer
71          ,disposition ,description ,cache ,id))
72
73 (defcustom mm-inline-media-tests
74   '(("image/jpeg"
75      mm-inline-image
76      (lambda (handle)
77        (mm-valid-and-fit-image-p 'jpeg handle)))
78     ("image/png"
79      mm-inline-image
80      (lambda (handle)
81        (mm-valid-and-fit-image-p 'png handle)))
82     ("image/gif"
83      mm-inline-image
84      (lambda (handle)
85        (mm-valid-and-fit-image-p 'gif handle)))
86     ("image/tiff"
87      mm-inline-image
88      (lambda (handle)
89        (mm-valid-and-fit-image-p 'tiff handle)) )
90     ("image/xbm"
91      mm-inline-image
92      (lambda (handle)
93        (mm-valid-and-fit-image-p 'xbm handle)))
94     ("image/x-xbitmap"
95      mm-inline-image
96      (lambda (handle)
97        (mm-valid-and-fit-image-p 'xbm handle)))
98     ("image/xpm"
99      mm-inline-image
100      (lambda (handle)
101        (mm-valid-and-fit-image-p 'xpm handle)))
102     ("image/x-pixmap"
103      mm-inline-image
104      (lambda (handle)
105        (mm-valid-and-fit-image-p 'xpm handle)))
106     ("image/bmp"
107      mm-inline-image
108      (lambda (handle)
109        (mm-valid-and-fit-image-p 'bmp handle)))
110     ("text/plain" mm-inline-text identity)
111     ("text/enriched" mm-inline-text identity)
112     ("text/richtext" mm-inline-text identity)
113     ("text/x-patch" mm-display-patch-inline
114      (lambda (handle)
115        (locate-library "diff-mode")))
116     ("text/html"
117      mm-inline-text
118      (lambda (handle)
119        (locate-library "w3")))
120     ("text/x-vcard"
121      mm-inline-text
122      (lambda (handle)
123        (or (featurep 'vcard)
124            (locate-library "vcard"))))
125     ("message/delivery-status" mm-inline-text identity)
126     ("message/rfc822" mm-inline-message identity)
127     ("text/.*" mm-inline-text identity)
128     ("audio/wav" mm-inline-audio
129      (lambda (handle)
130        (and (or (featurep 'nas-sound) (featurep 'native-sound))
131             (device-sound-enabled-p))))
132     ("audio/au"
133      mm-inline-audio
134      (lambda (handle)
135        (and (or (featurep 'nas-sound) (featurep 'native-sound))
136             (device-sound-enabled-p))))
137     ("application/pgp-signature" ignore identity)
138     ("multipart/alternative" ignore identity)
139     ("multipart/mixed" ignore identity)
140     ("multipart/related" ignore identity))
141   "Alist of media types/tests saying whether types can be displayed inline."
142   :type '(repeat (list (string :tag "MIME type")
143                        (function :tag "Display function")
144                        (function :tag "Display test")))
145   :group 'mime-display)
146
147 (defcustom mm-inlined-types
148   '("image/.*" "text/.*" "message/delivery-status" "message/rfc822"
149     "application/pgp-signature")
150   "List of media types that are to be displayed inline."
151   :type '(repeat string)
152   :group 'mime-display)
153   
154 (defcustom mm-automatic-display
155   '("text/plain" "text/enriched" "text/richtext" "text/html"
156     "text/x-vcard" "image/.*" "message/delivery-status" "multipart/.*"
157     "message/rfc822" "text/x-patch" "application/pgp-signature")
158   "A list of MIME types to be displayed automatically."
159   :type '(repeat string)
160   :group 'mime-display)
161
162 (defcustom mm-attachment-override-types '("text/x-vcard")
163   "Types to have \"attachment\" ignored if they can be displayed inline."
164   :type '(repeat string)
165   :group 'mime-display)
166
167 (defcustom mm-inline-override-types nil
168   "Types to be treated as attachments even if they can be displayed inline."
169   :type '(repeat string)
170   :group 'mime-display)
171
172 (defcustom mm-inline-override-types nil
173   "Types to be treated as attachments even if they can be displayed inline."
174   :type '(repeat string)
175   :group 'mime-display)
176
177 (defcustom mm-automatic-external-display nil
178   "List of MIME type regexps that will be displayed externally automatically."
179   :type '(repeat string)
180   :group 'mime-display)
181
182 (defcustom mm-discouraged-alternatives nil
183   "List of MIME types that are discouraged when viewing multipart/alternative.
184 Viewing agents are supposed to view the last possible part of a message,
185 as that is supposed to be the richest.  However, users may prefer other
186 types instead, and this list says what types are most unwanted.  If,
187 for instance, text/html parts are very unwanted, and text/richtech are
188 somewhat unwanted, then the value of this variable should be set
189 to:
190
191  (\"text/html\" \"text/richtext\")"
192   :type '(repeat string)
193   :group 'mime-display)
194
195 (defvar mm-tmp-directory
196   (cond ((fboundp 'temp-directory) (temp-directory))
197         ((boundp 'temporary-file-directory) temporary-file-directory)
198         ("/tmp/"))
199   "Where mm will store its temporary files.")
200
201 (defcustom mm-inline-large-images nil
202   "If non-nil, then all images fit in the buffer."
203   :type 'boolean
204   :group 'mime-display)
205
206 ;;; Internal variables.
207
208 (defvar mm-dissection-list nil)
209 (defvar mm-last-shell-command "")
210 (defvar mm-content-id-alist nil)
211
212 ;;; The functions.
213
214 (defun mm-dissect-buffer (&optional no-strict-mime)
215   "Dissect the current buffer and return a list of MIME handles."
216   (save-excursion
217     (let (ct ctl type subtype cte cd description id result)
218       (save-restriction
219         (mail-narrow-to-head)
220         (when (or no-strict-mime
221                   (mail-fetch-field "mime-version"))
222           (setq ct (mail-fetch-field "content-type")
223                 ctl (ignore-errors (mail-header-parse-content-type ct))
224                 cte (mail-fetch-field "content-transfer-encoding")
225                 cd (mail-fetch-field "content-disposition")
226                 description (mail-fetch-field "content-description")
227                 id (mail-fetch-field "content-id"))))
228       (if (or (not ctl)
229               (not (string-match "/" (car ctl))))
230           (mm-dissect-singlepart
231            '("text/plain") 
232            (and cte (intern (downcase (mail-header-remove-whitespace
233                                        (mail-header-remove-comments
234                                         cte)))))
235            no-strict-mime
236            (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
237            description)
238         (setq type (split-string (car ctl) "/"))
239         (setq subtype (cadr type)
240               type (pop type))
241         (setq
242          result
243          (cond
244           ((equal type "multipart")
245            (cons (car ctl) (mm-dissect-multipart ctl)))
246           (t
247            (mm-dissect-singlepart
248             ctl
249             (and cte (intern (downcase (mail-header-remove-whitespace
250                                         (mail-header-remove-comments
251                                          cte)))))
252             no-strict-mime
253             (and cd (ignore-errors (mail-header-parse-content-disposition cd)))
254             description id))))
255         (when id
256           (when (string-match " *<\\(.*\\)> *" id)
257             (setq id (match-string 1 id)))
258           (push (cons id result) mm-content-id-alist))
259         result))))
260
261 (defun mm-dissect-singlepart (ctl cte &optional force cdl description id)
262   (when (or force
263             (not (equal "text/plain" (car ctl))))
264     (let ((res (mm-make-handle
265                 (mm-copy-to-buffer) ctl cte nil cdl description nil id)))
266       (push (car res) mm-dissection-list)
267       res)))
268
269 (defun mm-remove-all-parts ()
270   "Remove all MIME handles."
271   (interactive)
272   (mapcar 'mm-remove-part mm-dissection-list)
273   (setq mm-dissection-list nil))
274
275 (defun mm-dissect-multipart (ctl)
276   (goto-char (point-min))
277   (let* ((boundary (concat "\n--" (mail-content-type-get ctl 'boundary)))
278          (close-delimiter (concat (regexp-quote boundary) "--[ \t]*$"))
279          start parts
280          (end (save-excursion
281                 (goto-char (point-max))
282                 (if (re-search-backward close-delimiter nil t)
283                     (match-beginning 0)
284                   (point-max)))))
285     (while (search-forward boundary end t)
286       (goto-char (match-beginning 0))
287       (when start
288         (save-excursion
289           (save-restriction
290             (narrow-to-region start (point))
291             (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
292       (forward-line 2)
293       (setq start (point)))
294     (when start
295       (save-excursion
296         (save-restriction
297           (narrow-to-region start end)
298           (setq parts (nconc (list (mm-dissect-buffer t)) parts)))))
299     (nreverse parts)))
300
301 (defun mm-copy-to-buffer ()
302   "Copy the contents of the current buffer to a fresh buffer."
303   (save-excursion
304     (let ((obuf (current-buffer))
305           beg)
306       (goto-char (point-min))
307       (search-forward-regexp "^\n" nil t)
308       (setq beg (point))
309       (set-buffer (generate-new-buffer " *mm*"))
310       (insert-buffer-substring obuf beg)
311       (current-buffer))))
312
313 (defun mm-display-part (handle &optional no-default)
314   "Display the MIME part represented by HANDLE.
315 Returns nil if the part is removed; inline if displayed inline;
316 external if displayed external."
317   (save-excursion
318     (mailcap-parse-mailcaps)
319     (if (mm-handle-displayed-p handle)
320         (mm-remove-part handle)
321       (let* ((type (mm-handle-media-type handle))
322              (method (mailcap-mime-info type)))
323         (if (mm-inlined-p handle)
324             (progn
325               (forward-line 1)
326               (mm-display-inline handle)
327               'inline)
328           (when (or method
329                     (not no-default))
330             (if (and (not method)
331                      (equal "text" (car (split-string type))))
332                 (progn
333                   (forward-line 1)
334                   (mm-insert-inline handle (mm-get-part handle))
335                   'inline)
336               (mm-display-external
337                handle (or method 'mailcap-save-binary-file))
338               'external)))))))
339
340 (defun mm-display-external (handle method)
341   "Display HANDLE using METHOD."
342   (mm-with-unibyte-buffer
343     (if (functionp method)
344         (let ((cur (current-buffer)))
345           (if (eq method 'mailcap-save-binary-file)
346               (progn
347                 (set-buffer (generate-new-buffer "*mm*"))
348                 (setq method nil))
349             (mm-insert-part handle)
350             (let ((win (get-buffer-window cur t)))
351               (when win
352                 (select-window win)))
353             (switch-to-buffer (generate-new-buffer "*mm*")))
354           (buffer-disable-undo)
355           (mm-set-buffer-file-coding-system mm-binary-coding-system)
356           (insert-buffer-substring cur)
357           (message "Viewing with %s" method)
358           (let ((mm (current-buffer))
359                 (non-viewer (assq 'non-viewer
360                                   (mailcap-mime-info
361                                    (mm-handle-media-type handle) t))))
362             (unwind-protect
363                 (if method
364                     (funcall method)
365                   (mm-save-part handle))
366               (when (and (not non-viewer)
367                          method)
368                 (mm-handle-set-undisplayer handle mm)))))
369       ;; The function is a string to be executed.
370       (mm-insert-part handle)
371       (let* ((dir (make-temp-name (expand-file-name "emm." mm-tmp-directory)))
372              (filename (mail-content-type-get
373                         (mm-handle-disposition handle) 'filename))
374              (mime-info (mailcap-mime-info
375                          (mm-handle-media-type handle) t))
376              (needsterm (or (assoc "needsterm" mime-info)
377                             (assoc "needsterminal" mime-info)))
378              (copiousoutput (assoc "copiousoutput" mime-info))
379              process file buffer)
380         ;; We create a private sub-directory where we store our files.
381         (make-directory dir)
382         (set-file-modes dir 448)
383         (if filename
384             (setq file (expand-file-name (file-name-nondirectory filename)
385                                          dir))
386           (setq file (make-temp-name (expand-file-name "mm." dir))))
387         (let ((coding-system-for-write mm-binary-coding-system))
388           (write-region (point-min) (point-max) file nil 'nomesg))
389         (message "Viewing with %s" method)
390         (unwind-protect
391             (setq process
392                   (cond (needsterm
393                          (start-process "*display*" nil
394                                         "xterm"
395                                         "-e" shell-file-name 
396                                         shell-command-switch
397                                         (mm-mailcap-command
398                                          method file (mm-handle-type handle))))
399                         (copiousoutput
400                          (start-process "*display*"
401                                         (setq buffer 
402                                               (generate-new-buffer "*mm*"))
403                                         shell-file-name
404                                         shell-command-switch
405                                         (mm-mailcap-command
406                                          method file (mm-handle-type handle)))
407                          (switch-to-buffer buffer))
408                         (t
409                          (start-process "*display*"
410                                         (setq buffer
411                                               (generate-new-buffer "*mm*"))
412                                         shell-file-name
413                                         shell-command-switch
414                                         (mm-mailcap-command
415                                          method file (mm-handle-type handle))))))
416           (mm-handle-set-undisplayer handle (cons file buffer)))
417         (message "Displaying %s..." (format method file))))))
418
419 (defun mm-mailcap-command (method file type-list)
420   (let ((ctl (cdr type-list))
421         (beg 0)
422         out sub total)
423     (while (string-match "%{\\([^}]+\\)}\\|%s\\|%t" method beg)
424       (push (substring method beg (match-beginning 0)) out)
425       (setq beg (match-end 0)
426             total (match-string 0 method)
427             sub (match-string 1 method))
428       (cond
429        ((string= total "%s")
430         (push (mm-quote-arg file) out))
431        ((string= total "%t")
432         (push (mm-quote-arg (car type-list)) out))
433        (t
434         (push (mm-quote-arg (or (cdr (assq (intern sub) ctl)) "")) out))))
435     (push (substring method beg (length method)) out)
436     (mapconcat 'identity (nreverse out) "")))
437     
438 (defun mm-remove-parts (handles)
439   "Remove the displayed MIME parts represented by HANDLE."
440   (if (and (listp handles)
441            (bufferp (car handles)))
442       (mm-remove-part handles)
443     (let (handle)
444       (while (setq handle (pop handles))
445         (cond
446          ((stringp handle)
447           ;; Do nothing.
448           )
449          ((and (listp handle)
450                (stringp (car handle)))
451           (mm-remove-parts (cdr handle)))
452          (t
453           (mm-remove-part handle)))))))
454
455 (defun mm-destroy-parts (handles)
456   "Remove the displayed MIME parts represented by HANDLE."
457   (if (and (listp handles)
458            (bufferp (car handles)))
459       (mm-destroy-part handles)
460     (let (handle)
461       (while (setq handle (pop handles))
462         (cond
463          ((stringp handle)
464           ;; Do nothing.
465           )
466          ((and (listp handle)
467                (stringp (car handle)))
468           (mm-destroy-parts (cdr handle)))
469          (t
470           (mm-destroy-part handle)))))))
471
472 (defun mm-remove-part (handle)
473   "Remove the displayed MIME part represented by HANDLE."
474   (when (listp handle)
475     (let ((object (mm-handle-undisplayer handle)))
476       (ignore-errors
477         (cond
478          ;; Internally displayed part.
479          ((mm-annotationp object)
480           (delete-annotation object))
481          ((or (functionp object)
482               (and (listp object)
483                    (eq (car object) 'lambda)))
484           (funcall object))
485          ;; Externally displayed part.
486          ((consp object)
487           (ignore-errors (delete-file (car object)))
488           (ignore-errors (delete-directory (file-name-directory (car object))))
489           (ignore-errors (kill-buffer (cdr object))))
490          ((bufferp object)
491           (when (buffer-live-p object)
492             (kill-buffer object)))))
493       (mm-handle-set-undisplayer handle nil))))
494
495 (defun mm-display-inline (handle)
496   (let* ((type (mm-handle-media-type handle))
497          (function (cadr (mm-assoc-string-match mm-inline-media-tests type))))
498     (funcall function handle)
499     (goto-char (point-min))))
500
501 (defun mm-assoc-string-match (alist type)
502   (dolist (elem alist)
503     (when (string-match (car elem) type)
504       (return elem))))
505
506 (defun mm-inlinable-p (handle)
507   "Say whether HANDLE can be displayed inline."
508   (let ((alist mm-inline-media-tests)
509         (type (mm-handle-media-type handle))
510         test)
511     (while alist
512       (when (string-match (caar alist) type)
513         (setq test (caddar alist)
514               alist nil)
515         (setq test (funcall test handle)))
516       (pop alist))
517     test))
518
519 (defun mm-automatic-display-p (handle)
520   "Say whether the user wants HANDLE to be displayed automatically."
521   (let ((methods mm-automatic-display)
522         (type (mm-handle-media-type handle))
523         method result)
524     (while (setq method (pop methods))
525       (when (and (not (mm-inline-override-p handle))
526                  (string-match method type)
527                  (mm-inlinable-p handle))
528         (setq result t
529               methods nil)))
530     result))
531
532 (defun mm-inlined-p (handle)
533   "Say whether the user wants HANDLE to be displayed automatically."
534   (let ((methods mm-inlined-types)
535         (type (mm-handle-media-type handle))
536         method result)
537     (while (setq method (pop methods))
538       (when (and (not (mm-inline-override-p handle))
539                  (string-match method type)
540                  (mm-inlinable-p handle))
541         (setq result t
542               methods nil)))
543     result))
544
545 (defun mm-attachment-override-p (handle)
546   "Say whether HANDLE should have attachment behavior overridden."
547   (let ((types mm-attachment-override-types)
548         (type (mm-handle-media-type handle))
549         ty)
550     (catch 'found
551       (while (setq ty (pop types))
552         (when (and (string-match ty type)
553                    (mm-inlinable-p handle))
554           (throw 'found t))))))
555
556 (defun mm-inline-override-p (handle)
557   "Say whether HANDLE should have inline behavior overridden."
558   (let ((types mm-inline-override-types)
559         (type (mm-handle-media-type handle))
560         ty)
561     (catch 'found
562       (while (setq ty (pop types))
563         (when (string-match ty type)
564           (throw 'found t))))))
565
566 (defun mm-automatic-external-display-p (type)
567   "Return the user-defined method for TYPE."
568   (let ((methods mm-automatic-external-display)
569         method result)
570     (while (setq method (pop methods))
571       (when (string-match method type)
572         (setq result t
573               methods nil)))
574     result))
575
576 (defun mm-destroy-part (handle)
577   "Destroy the data structures connected to HANDLE."
578   (when (listp handle)
579     (mm-remove-part handle)
580     (when (buffer-live-p (mm-handle-buffer handle))
581       (kill-buffer (mm-handle-buffer handle)))))
582
583 (defun mm-handle-displayed-p (handle)
584   "Say whether HANDLE is displayed or not."
585   (mm-handle-undisplayer handle))
586
587 ;;;
588 ;;; Functions for outputting parts
589 ;;;
590
591 (defun mm-get-part (handle)
592   "Return the contents of HANDLE as a string."
593   (mm-with-unibyte-buffer
594     (mm-insert-part handle)
595     (buffer-string)))
596
597 (defun mm-insert-part (handle)
598   "Insert the contents of HANDLE in the current buffer."
599   (let ((cur (current-buffer)))
600     (save-excursion
601       (if (member (mm-handle-media-supertype handle) '("text" "message"))
602           (with-temp-buffer
603             (insert-buffer-substring (mm-handle-buffer handle))
604             (mm-decode-content-transfer-encoding
605              (mm-handle-encoding handle)
606              (mm-handle-media-type handle))
607             (let ((temp (current-buffer)))
608               (set-buffer cur)
609               (insert-buffer-substring temp)))
610         (mm-with-unibyte-buffer
611           (insert-buffer-substring (mm-handle-buffer handle))
612           (mm-decode-content-transfer-encoding
613            (mm-handle-encoding handle)
614            (mm-handle-media-type handle))
615           (let ((temp (current-buffer)))
616             (set-buffer cur)
617             (insert-buffer-substring temp)))))))
618
619 (defvar mm-default-directory nil)
620
621 (defun mm-save-part (handle)
622   "Write HANDLE to a file."
623   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
624          (filename (mail-content-type-get
625                     (mm-handle-disposition handle) 'filename))
626          file)
627     (when filename
628       (setq filename (file-name-nondirectory filename)))
629     (setq file
630           (read-file-name "Save MIME part to: "
631                           (expand-file-name
632                            (or filename name "")
633                            (or mm-default-directory default-directory))))
634     (setq mm-default-directory (file-name-directory file))
635     (when (or (not (file-exists-p file))
636               (yes-or-no-p (format "File %s already exists; overwrite? "
637                                    file)))
638       (mm-save-part-to-file handle file))))
639
640 (defun mm-save-part-to-file (handle file)
641   (mm-with-unibyte-buffer
642     (mm-insert-part handle)
643     (let ((coding-system-for-write 'binary)
644           ;; Don't re-compress .gz & al.  Arguably we should make
645           ;; `file-name-handler-alist' nil, but that would chop
646           ;; ange-ftp, which is reasonable to use here.
647           (inhibit-file-name-operation 'write-region)
648           (inhibit-file-name-handlers
649            (cons 'jka-compr-handler inhibit-file-name-handlers)))
650       (write-region (point-min) (point-max) file))))
651
652 (defun mm-pipe-part (handle)
653   "Pipe HANDLE to a process."
654   (let* ((name (mail-content-type-get (mm-handle-type handle) 'name))
655          (command
656           (read-string "Shell command on MIME part: " mm-last-shell-command)))
657     (mm-with-unibyte-buffer
658       (mm-insert-part handle)
659       (shell-command-on-region (point-min) (point-max) command nil))))
660
661 (defun mm-interactively-view-part (handle)
662   "Display HANDLE using METHOD."
663   (let* ((type (mm-handle-media-type handle))
664          (methods
665           (mapcar (lambda (i) (list (cdr (assoc 'viewer i))))
666                   (mailcap-mime-info type 'all)))
667          (method (completing-read "Viewer: " methods)))
668     (mm-display-external (copy-sequence handle) method)))
669
670 (defun mm-preferred-alternative (handles &optional preferred)
671   "Say which of HANDLES are preferred."
672   (let ((prec (if preferred (list preferred)
673                 (mm-preferred-alternative-precedence handles)))
674         p h result type handle)
675     (while (setq p (pop prec))
676       (setq h handles)
677       (while h
678         (setq handle (car h))
679         (setq type (mm-handle-media-type handle))
680         (when (and (equal p type)
681                    (mm-automatic-display-p handle)
682                    (or (stringp (car handle))
683                        (not (mm-handle-disposition handle))
684                        (equal (car (mm-handle-disposition handle))
685                               "inline")))
686           (setq result handle
687                 h nil
688                 prec nil))
689         (pop h)))
690     result))
691
692 (defun mm-preferred-alternative-precedence (handles)
693   "Return the precedence based on HANDLES and mm-discouraged-alternatives."
694   (let ((seq (nreverse (mapcar (lambda (h)
695                                  (mm-handle-media-type h))
696                                handles))))
697     (dolist (disc (reverse mm-discouraged-alternatives))
698       (dolist (elem (copy-sequence seq))
699         (when (string-match disc elem)
700           (setq seq (nconc (delete elem seq) (list elem))))))
701     seq))
702
703 (defun mm-get-content-id (id)
704   "Return the handle(s) referred to by ID."
705   (cdr (assoc id mm-content-id-alist)))
706
707 (defun mm-get-image (handle)
708   "Return an image instance based on HANDLE."
709   (let ((type (mm-handle-media-subtype handle))
710         spec)
711     ;; Allow some common translations.
712     (setq type
713           (cond
714            ((equal type "x-pixmap")
715             "xpm")
716            ((equal type "x-xbitmap")
717             "xbm")
718            (t type)))
719     (or (mm-handle-cache handle)
720         (mm-with-unibyte-buffer
721           (mm-insert-part handle)
722           (prog1
723               (setq spec
724                     (ignore-errors
725                       (cond
726                        ((equal type "xbm")
727                         ;; xbm images require special handling, since
728                         ;; the only way to create glyphs from these
729                         ;; (without a ton of work) is to write them
730                         ;; out to a file, and then create a file
731                         ;; specifier.
732                         (let ((file (make-temp-name
733                                      (expand-file-name "emm.xbm"
734                                                        mm-tmp-directory))))
735                           (unwind-protect
736                               (progn
737                                 (write-region (point-min) (point-max) file)
738                                 (make-glyph (list (cons 'x file))))
739                             (ignore-errors
740                               (delete-file file)))))
741                        (t
742                         (make-glyph
743                          (vector (intern type) :data (buffer-string)))))))
744             (mm-handle-set-cache handle spec))))))
745
746 (defun mm-image-fit-p (handle)
747   "Say whether the image in HANDLE will fit the current window."
748   (let ((image (mm-get-image handle)))
749     (or mm-inline-large-images
750         (and (< (glyph-width image) (window-pixel-width))
751              (< (glyph-height image) (window-pixel-height))))))
752
753 (defun mm-valid-image-format-p (format)
754   "Say whether FORMAT can be displayed natively by Emacs."
755   (and (fboundp 'valid-image-instantiator-format-p)
756        (valid-image-instantiator-format-p format)))
757
758 (defun mm-valid-and-fit-image-p (format handle)
759   "Say whether FORMAT can be displayed natively and HANDLE fits the window."
760   (and window-system
761        (mm-valid-image-format-p format)
762        (mm-image-fit-p handle)))
763
764 (provide 'mm-decode)
765
766 ;; mm-decode.el ends here