Synch with `t-gnus-6_14' and Gnus.
[elisp/gnus.git-] / lisp / mm-util.el
1 ;;; mm-util.el --- Utility functions for MIME things
2 ;; Copyright (C) 1998, 1999, 2000 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 (eval-when-compile (require 'static))
28
29 (require 'mail-prsvr)
30
31 (defvar mm-mime-mule-charset-alist
32   '((us-ascii ascii)
33     (iso-8859-1 latin-iso8859-1)
34     (iso-8859-2 latin-iso8859-2)
35     (iso-8859-3 latin-iso8859-3)
36     (iso-8859-4 latin-iso8859-4)
37     (iso-8859-5 cyrillic-iso8859-5)
38     ;; Non-mule (X)Emacs uses the last mule-charset for 8bit characters.
39     ;; The fake mule-charset, gnus-koi8-r, tells Gnus that the default 
40     ;; charset is koi8-r, not iso-8859-5.
41     (koi8-r cyrillic-iso8859-5 gnus-koi8-r)
42     (iso-8859-6 arabic-iso8859-6)
43     (iso-8859-7 greek-iso8859-7)
44     (iso-8859-8 hebrew-iso8859-8)
45     (iso-8859-9 latin-iso8859-9)
46     (viscii vietnamese-viscii-lower)
47     (iso-2022-jp latin-jisx0201 japanese-jisx0208 japanese-jisx0208-1978)
48     (euc-kr korean-ksc5601)
49     (cn-gb-2312 chinese-gb2312)
50     (cn-big5 chinese-big5-1 chinese-big5-2)
51     (tibetan tibetan)
52     (thai-tis620 thai-tis620)
53     (iso-2022-7bit ethiopic arabic-1-column arabic-2-column)
54     (iso-2022-jp-2 latin-iso8859-1 greek-iso8859-7
55                    latin-jisx0201 japanese-jisx0208-1978
56                    chinese-gb2312 japanese-jisx0208
57                    korean-ksc5601 japanese-jisx0212
58                    katakana-jisx0201)
59     (iso-2022-int-1 latin-iso8859-1 greek-iso8859-7
60                     latin-jisx0201 japanese-jisx0208-1978
61                     chinese-gb2312 japanese-jisx0208
62                     korean-ksc5601 japanese-jisx0212
63                     chinese-cns11643-1 chinese-cns11643-2)
64     (iso-2022-int-1 latin-iso8859-1 latin-iso8859-2
65                     cyrillic-iso8859-5 greek-iso8859-7
66                     latin-jisx0201 japanese-jisx0208-1978
67                     chinese-gb2312 japanese-jisx0208
68                     korean-ksc5601 japanese-jisx0212
69                     chinese-cns11643-1 chinese-cns11643-2
70                     chinese-cns11643-3 chinese-cns11643-4
71                     chinese-cns11643-5 chinese-cns11643-6
72                     chinese-cns11643-7)
73     (utf-8 unicode-a unicode-b unicode-c unicode-d unicode-e))
74   "Alist of MIME-charset/MULE-charsets.")
75
76 (eval-and-compile
77   (mapcar
78    (lambda (elem)
79      (let ((nfunc (intern (format "mm-%s" (car elem)))))
80        (if (fboundp (car elem))
81            (defalias nfunc (car elem))
82          (defalias nfunc (cdr elem)))))
83    '((decode-coding-string . (lambda (s a) s))
84      (encode-coding-string . (lambda (s a) s))
85      (encode-coding-region . ignore)
86      (coding-system-list . ignore)
87      (decode-coding-region . ignore)
88      (char-int . identity)
89      (device-type . ignore)
90      (coding-system-equal . equal)
91      (annotationp . ignore)
92      (set-buffer-file-coding-system . ignore)
93      (make-char
94       . (lambda (charset int)
95           (int-to-char int)))
96      (read-coding-system
97       . (lambda (prompt)
98           "Prompt the user for a coding system."
99           (completing-read
100            prompt (mapcar (lambda (s) (list (symbol-name (car s))))
101                           mm-mime-mule-charset-alist))))
102      (read-charset
103       . (lambda (prompt)
104           "Return a charset."
105           (intern
106            (completing-read
107             prompt
108             (mapcar (lambda (e) (list (symbol-name (car e))))
109                     mm-mime-mule-charset-alist)
110             nil t)))))))
111
112 (eval-and-compile
113   (defalias 'mm-char-or-char-int-p
114     (cond 
115      ((fboundp 'char-or-char-int-p) 'char-or-char-int-p)
116      ((fboundp 'char-valid-p) 'char-valid-p) 
117      (t 'identity))))
118
119 (defvar mm-coding-system-list nil)
120 (defun mm-get-coding-system-list ()
121   "Get the coding system list."
122   (or mm-coding-system-list
123       (setq mm-coding-system-list (mm-coding-system-list))))
124
125 (defvar mm-charset-synonym-alist
126   '((big5 . cn-big5)
127     (gb2312 . cn-gb-2312)
128     (x-ctext . ctext))
129   "A mapping from invalid charset names to the real charset names.")
130
131 (defun mm-coding-system-p (sym)
132   "Return non-nil if SYM is a coding system."
133   (or (and (fboundp 'coding-system-p) (coding-system-p sym))
134       (memq sym (mm-get-coding-system-list))))
135
136 (defvar mm-binary-coding-system
137   (cond 
138    ((mm-coding-system-p 'binary) 'binary)
139    ((mm-coding-system-p 'no-conversion) 'no-conversion)
140    (t nil))
141   "100% binary coding system.")
142
143 (defvar mm-text-coding-system
144   (or (if (memq system-type '(windows-nt ms-dos ms-windows))
145           (and (mm-coding-system-p 'raw-text-dos) 'raw-text-dos)
146         (and (mm-coding-system-p 'raw-text) 'raw-text))
147       mm-binary-coding-system)
148   "Text-safe coding system (For removing ^M).")
149
150 (defvar mm-text-coding-system-for-write nil
151   "Text coding system for write.")
152
153 (defvar mm-auto-save-coding-system
154   (cond 
155    ((mm-coding-system-p 'emacs-mule)
156     (if (memq system-type '(windows-nt ms-dos ms-windows))
157         (if (mm-coding-system-p 'emacs-mule-dos) 
158             'emacs-mule-dos mm-binary-coding-system)
159       'emacs-mule))
160    ((mm-coding-system-p 'escape-quoted) 'escape-quoted)
161    (t mm-binary-coding-system))
162   "Coding system of auto save file.")
163
164 ;;; Internal variables:
165
166 ;;; Functions:
167
168 (defun mm-mule-charset-to-mime-charset (charset)
169   "Return the MIME charset corresponding to MULE CHARSET."
170   (let ((alist mm-mime-mule-charset-alist)
171         out)
172     (while alist
173       (when (memq charset (cdar alist))
174         (setq out (caar alist)
175               alist nil))
176       (pop alist))
177     out))
178
179 (defun mm-charset-to-coding-system (charset &optional lbt)
180   "Return coding-system corresponding to CHARSET.
181 CHARSET is a symbol naming a MIME charset.
182 If optional argument LBT (`unix', `dos' or `mac') is specified, it is
183 used as the line break code type of the coding system."
184   (when (stringp charset)
185     (setq charset (intern (downcase charset))))
186   (setq charset
187         (or (cdr (assq charset mm-charset-synonym-alist))
188             charset))
189   (when lbt
190     (setq charset (intern (format "%s-%s" charset lbt))))
191   (cond
192    ;; Running in a non-MULE environment.
193    ((null (mm-get-coding-system-list))
194     charset)
195    ;; ascii
196    ((eq charset 'us-ascii)
197     'ascii)
198    ;; Check to see whether we can handle this charset.
199    ((memq charset (mm-get-coding-system-list))
200     charset)
201    ;; Nope.
202    (t
203     nil)))
204
205 (static-if (fboundp 'subst-char-in-string)
206     (defsubst mm-replace-chars-in-string (string from to)
207       (subst-char-in-string from to string))
208   (defun mm-replace-chars-in-string (string from to)
209     "Replace characters in STRING from FROM to TO."
210     (let ((string (substring string 0)) ;Copy string.
211           (len (length string))
212           (idx 0))
213       ;; Replace all occurrences of FROM with TO.
214       (while (< idx len)
215         (when (= (aref string idx) from)
216           (aset string idx to))
217         (setq idx (1+ idx)))
218       string)))
219
220 (defsubst mm-enable-multibyte ()
221   "Enable multibyte in the current buffer."
222   (when (and (fboundp 'set-buffer-multibyte)
223              (boundp 'enable-multibyte-characters)
224              (default-value 'enable-multibyte-characters))
225     (set-buffer-multibyte t)))
226
227 (defsubst mm-disable-multibyte ()
228   "Disable multibyte in the current buffer."
229   (when (fboundp 'set-buffer-multibyte)
230     (set-buffer-multibyte nil)))
231
232 (defsubst mm-enable-multibyte-mule4 ()
233   "Enable multibyte in the current buffer.
234 Only used in Emacs Mule 4."
235   (when (and (fboundp 'set-buffer-multibyte)
236              (boundp 'enable-multibyte-characters)
237              (default-value 'enable-multibyte-characters)
238              (not (charsetp 'eight-bit-control)))
239     (set-buffer-multibyte t)))
240
241 (defsubst mm-disable-multibyte-mule4 ()
242   "Disable multibyte in the current buffer.
243 Only used in Emacs Mule 4."
244   (when (and (fboundp 'set-buffer-multibyte)
245              (not (charsetp 'eight-bit-control)))
246     (set-buffer-multibyte nil)))
247
248 (defun mm-preferred-coding-system (charset)
249   ;; A typo in some Emacs versions.
250   (or (get-charset-property charset 'prefered-coding-system)
251       (get-charset-property charset 'preferred-coding-system)))
252
253 (defun mm-charset-after (&optional pos)
254   "Return charset of a character in current buffer at position POS.
255 If POS is nil, it defauls to the current point.
256 If POS is out of range, the value is nil.
257 If the charset is `composition', return the actual one."
258   (let ((char (char-after pos)) charset)
259     (if (< (mm-char-int char) 128)
260         (setq charset 'ascii)
261       ;; charset-after is fake in some Emacsen.
262       (setq charset (and (fboundp 'char-charset) (char-charset char)))
263       (if (eq charset 'composition)
264           (let ((p (or pos (point))))
265             (cadr (find-charset-region p (1+ p))))
266         (if (and charset (not (memq charset '(ascii eight-bit-control
267                                                     eight-bit-graphic))))
268             charset
269           (or
270            mail-parse-mule-charset ;; cached mule-charset
271            (progn
272              (setq mail-parse-mule-charset
273                    (and (boundp 'current-language-environment)
274                       (car (last 
275                             (assq 'charset 
276                                   (assoc current-language-environment 
277                                          language-info-alist))))))
278              (if (or (not mail-parse-mule-charset)
279                      (eq mail-parse-mule-charset 'ascii))
280                  (setq mail-parse-mule-charset
281                        (or (car (last (assq mail-parse-charset
282                                             mm-mime-mule-charset-alist)))
283                            'latin-iso8859-1)))
284              mail-parse-mule-charset)))))))
285
286 (defun mm-mime-charset (charset)
287   "Return the MIME charset corresponding to the MULE CHARSET."
288   (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
289       ;; This exists in Emacs 20.
290       (or
291        (and (mm-preferred-coding-system charset)
292             (coding-system-get
293              (mm-preferred-coding-system charset) 'mime-charset))
294        (and (eq charset 'ascii)
295             'us-ascii)
296        (mm-preferred-coding-system charset)
297        (mm-mule-charset-to-mime-charset charset))
298     ;; This is for XEmacs.
299     (mm-mule-charset-to-mime-charset charset)))
300
301 (defun mm-delete-duplicates (list)
302   "Simple  substitute for CL `delete-duplicates', testing with `equal'."
303   (let (result head)
304     (while list
305       (setq head (car list))
306       (setq list (delete head list))
307       (setq result (cons head result)))
308     (nreverse result)))
309
310 (defun mm-find-mime-charset-region (b e)
311   "Return the MIME charsets needed to encode the region between B and E."
312   (let ((charsets (mapcar 'mm-mime-charset
313                           (delq 'ascii
314                                 (mm-find-charset-region b e)))))
315     (when (memq 'iso-2022-jp-2 charsets)
316       (setq charsets (delq 'iso-2022-jp charsets)))
317     (setq charsets (mm-delete-duplicates charsets))
318     (if (and (> (length charsets) 1)
319              (fboundp 'find-coding-systems-region)
320              (memq 'utf-8 (find-coding-systems-region b e)))
321         '(utf-8)
322       charsets)))
323
324 (defsubst mm-multibyte-p ()
325   "Say whether multibyte is enabled."
326   (if (boundp 'enable-multibyte-characters)
327       enable-multibyte-characters
328     (featurep 'mule)))
329
330 (defmacro mm-with-unibyte-buffer (&rest forms)
331   "Create a temporary buffer, and evaluate FORMS there like `progn'.
332 See also `with-temp-file' and `with-output-to-string'."
333   (let ((temp-buffer (make-symbol "temp-buffer"))
334         (multibyte (make-symbol "multibyte")))
335     `(if (or (featurep 'xemacs)
336              (not (boundp 'enable-multibyte-characters)))
337          (with-temp-buffer ,@forms)
338        (let ((,multibyte (default-value 'enable-multibyte-characters))
339              ,temp-buffer)
340          (unwind-protect
341              (progn
342                (setq-default enable-multibyte-characters nil)
343                (setq ,temp-buffer
344                      (get-buffer-create (generate-new-buffer-name " *temp*")))
345                (unwind-protect
346                    (with-current-buffer ,temp-buffer
347                      (let ((buffer-file-coding-system mm-binary-coding-system)
348                            (coding-system-for-read mm-binary-coding-system)
349                            (coding-system-for-write mm-binary-coding-system))
350                        ,@forms))
351                  (and (buffer-name ,temp-buffer)
352                       (kill-buffer ,temp-buffer))))
353            (setq-default enable-multibyte-characters ,multibyte))))))
354 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
355 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
356
357 (defmacro mm-with-unibyte-current-buffer (&rest forms)
358   "Evaluate FORMS there like `progn' in current buffer."
359   (let ((multibyte (make-symbol "multibyte")))
360     `(if (or (featurep 'xemacs)
361              (not (fboundp 'set-buffer-multibyte))
362              (charsetp 'eight-bit-control)) ;; For Emacs Mule 4 only.
363          (progn
364            ,@forms)
365        (let ((,multibyte (default-value 'enable-multibyte-characters)))
366          (unwind-protect
367              (let ((buffer-file-coding-system mm-binary-coding-system)
368                    (coding-system-for-read mm-binary-coding-system)
369                    (coding-system-for-write mm-binary-coding-system))
370                (set-buffer-multibyte nil)
371                (setq-default enable-multibyte-characters nil)
372                ,@forms)
373            (setq-default enable-multibyte-characters ,multibyte)
374            (set-buffer-multibyte ,multibyte))))))
375 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
376 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
377
378 (defmacro mm-with-unibyte (&rest forms)
379   "Set default `enable-multibyte-characters' to `nil', eval the FORMS."
380   (let ((multibyte (make-symbol "multibyte")))
381     `(if (or (featurep 'xemacs)
382              (not (boundp 'enable-multibyte-characters)))
383          (progn ,@forms)
384        (let ((,multibyte (default-value 'enable-multibyte-characters)))
385          (unwind-protect
386              (progn
387                (setq-default enable-multibyte-characters nil)
388                ,@forms)
389            (setq-default enable-multibyte-characters ,multibyte))))))
390 (put 'mm-with-unibyte 'lisp-indent-function 0)
391 (put 'mm-with-unibyte 'edebug-form-spec '(body))
392
393 (defun mm-find-charset-region (b e)
394   "Return a list of charsets in the region."
395   (cond
396    ((and (mm-multibyte-p)
397          (fboundp 'find-charset-region))
398     ;; Remove composition since the base charsets have been included.
399     (delq 'composition (find-charset-region b e)))
400    (t
401     ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
402     (save-excursion
403       (save-restriction
404         (narrow-to-region b e)
405         (goto-char (point-min))
406         (skip-chars-forward "\0-\177")
407         (if (eobp)
408             '(ascii)
409           (let (charset)
410             (setq charset
411                   (and (boundp 'current-language-environment)
412                        (car (last (assq 'charset 
413                                         (assoc current-language-environment 
414                                                language-info-alist))))))
415             (if (eq charset 'ascii) (setq charset nil))
416             (or charset
417                 (setq charset
418                       (car (last (assq mail-parse-charset
419                                        mm-mime-mule-charset-alist)))))
420             (list 'ascii (or charset 'latin-iso8859-1)))))))))
421
422 (static-if (fboundp 'shell-quote-argument)
423     (defalias 'mm-quote-arg 'shell-quote-argument)
424   (defun mm-quote-arg (arg)
425     "Return a version of ARG that is safe to evaluate in a shell."
426     (let ((pos 0) new-pos accum)
427       ;; *** bug: we don't handle newline characters properly
428       (while (setq new-pos (string-match "[]*[;!'`\"$\\& \t{} |()<>]" arg pos))
429         (push (substring arg pos new-pos) accum)
430         (push "\\" accum)
431         (push (list (aref arg new-pos)) accum)
432         (setq pos (1+ new-pos)))
433       (if (= pos 0)
434           arg
435         (apply 'concat (nconc (nreverse accum) (list (substring arg pos))))))))
436
437 (defun mm-auto-mode-alist ()
438   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
439   (let ((alist auto-mode-alist)
440         out)
441     (while alist
442       (when (listp (cdar alist))
443         (push (car alist) out))
444       (pop alist))
445     (nreverse out)))
446
447 (defvar mm-inhibit-file-name-handlers
448   '(jka-compr-handler)
449   "A list of handlers doing (un)compression (etc) thingies.")
450
451 (defun mm-insert-file-contents (filename &optional visit beg end replace
452                                          inhibit)
453   "Like `insert-file-contents', q.v., but only reads in the file.
454 A buffer may be modified in several ways after reading into the buffer due
455 to advanced Emacs features, such as file-name-handlers, format decoding,
456 find-file-hooks, etc.
457 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers.
458   This function ensures that none of these modifications will take place."
459   (let ((format-alist nil)
460         (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
461         (default-major-mode 'fundamental-mode)
462         (enable-local-variables nil)
463         (after-insert-file-functions nil)
464         (enable-local-eval nil)
465         (find-file-hooks nil)
466         (inhibit-file-name-operation (if inhibit 
467                                          'insert-file-contents
468                                        inhibit-file-name-operation))
469         (inhibit-file-name-handlers
470          (if inhibit
471              (append mm-inhibit-file-name-handlers 
472                      inhibit-file-name-handlers)
473            inhibit-file-name-handlers)))
474     (insert-file-contents filename visit beg end replace)))
475
476 (defun mm-append-to-file (start end filename &optional codesys inhibit)
477   "Append the contents of the region to the end of file FILENAME.
478 When called from a function, expects three arguments,
479 START, END and FILENAME.  START and END are buffer positions
480 saying what text to write.
481 Optional fourth argument specifies the coding system to use when
482 encoding the file.
483 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers."
484   (let ((coding-system-for-write 
485          (or codesys mm-text-coding-system-for-write 
486              mm-text-coding-system))
487         (inhibit-file-name-operation (if inhibit 
488                                          'append-to-file
489                                        inhibit-file-name-operation))
490         (inhibit-file-name-handlers
491          (if inhibit
492              (append mm-inhibit-file-name-handlers 
493                      inhibit-file-name-handlers)
494            inhibit-file-name-handlers)))
495     (append-to-file start end filename)))
496
497 (defun mm-write-region (start end filename &optional append visit lockname 
498                               coding-system inhibit)
499
500   "Like `write-region'.
501 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers."
502   (let ((coding-system-for-write 
503          (or coding-system mm-text-coding-system-for-write 
504              mm-text-coding-system))
505         (inhibit-file-name-operation (if inhibit 
506                                          'write-region
507                                        inhibit-file-name-operation))
508         (inhibit-file-name-handlers
509          (if inhibit
510              (append mm-inhibit-file-name-handlers 
511                      inhibit-file-name-handlers)
512            inhibit-file-name-handlers)))
513     (write-region start end filename append visit lockname)))
514
515 (provide 'mm-util)
516
517 ;;; mm-util.el ends here