Synch with Wanderlust.
[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          (progn
363            ,@forms)
364        (let ((,multibyte (default-value 'enable-multibyte-characters)))
365          (unwind-protect
366              (let ((buffer-file-coding-system mm-binary-coding-system)
367                    (coding-system-for-read mm-binary-coding-system)
368                    (coding-system-for-write mm-binary-coding-system))
369                (set-buffer-multibyte nil)
370                (setq-default enable-multibyte-characters nil)
371                ,@forms)
372            (setq-default enable-multibyte-characters ,multibyte)
373            (set-buffer-multibyte ,multibyte))))))
374 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
375 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
376
377 (defmacro mm-with-unibyte-current-buffer-mule4 (&rest forms)
378   "Evaluate FORMS there like `progn' in current buffer.
379 Mule4 only."
380   (let ((multibyte (make-symbol "multibyte")))
381     `(if (or (featurep 'xemacs)
382              (not (fboundp 'set-buffer-multibyte))
383              (charsetp 'eight-bit-control)) ;; For Emacs Mule 4 only.
384          (progn
385            ,@forms)
386        (let ((,multibyte (default-value 'enable-multibyte-characters)))
387          (unwind-protect
388              (let ((buffer-file-coding-system mm-binary-coding-system)
389                    (coding-system-for-read mm-binary-coding-system)
390                    (coding-system-for-write mm-binary-coding-system))
391                (set-buffer-multibyte nil)
392                (setq-default enable-multibyte-characters nil)
393                ,@forms)
394            (setq-default enable-multibyte-characters ,multibyte)
395            (set-buffer-multibyte ,multibyte))))))
396 (put 'mm-with-unibyte-current-buffer-mule4 'lisp-indent-function 0)
397 (put 'mm-with-unibyte-current-buffer-mule4 'edebug-form-spec '(body))
398
399 (defmacro mm-with-unibyte (&rest forms)
400   "Set default `enable-multibyte-characters' to `nil', eval the FORMS."
401   (let ((multibyte (make-symbol "multibyte")))
402     `(if (or (featurep 'xemacs)
403              (not (boundp 'enable-multibyte-characters)))
404          (progn ,@forms)
405        (let ((,multibyte (default-value 'enable-multibyte-characters)))
406          (unwind-protect
407              (progn
408                (setq-default enable-multibyte-characters nil)
409                ,@forms)
410            (setq-default enable-multibyte-characters ,multibyte))))))
411 (put 'mm-with-unibyte 'lisp-indent-function 0)
412 (put 'mm-with-unibyte 'edebug-form-spec '(body))
413
414 (defun mm-find-charset-region (b e)
415   "Return a list of charsets in the region."
416   (cond
417    ((and (mm-multibyte-p)
418          (fboundp 'find-charset-region))
419     ;; Remove composition since the base charsets have been included.
420     (delq 'composition (find-charset-region b e)))
421    (t
422     ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
423     (save-excursion
424       (save-restriction
425         (narrow-to-region b e)
426         (goto-char (point-min))
427         (skip-chars-forward "\0-\177")
428         (if (eobp)
429             '(ascii)
430           (let (charset)
431             (setq charset
432                   (and (boundp 'current-language-environment)
433                        (car (last (assq 'charset 
434                                         (assoc current-language-environment 
435                                                language-info-alist))))))
436             (if (eq charset 'ascii) (setq charset nil))
437             (or charset
438                 (setq charset
439                       (car (last (assq mail-parse-charset
440                                        mm-mime-mule-charset-alist)))))
441             (list 'ascii (or charset 'latin-iso8859-1)))))))))
442
443 (static-if (fboundp 'shell-quote-argument)
444     (defalias 'mm-quote-arg 'shell-quote-argument)
445   (defun mm-quote-arg (arg)
446     "Return a version of ARG that is safe to evaluate in a shell."
447     (let ((pos 0) new-pos accum)
448       ;; *** bug: we don't handle newline characters properly
449       (while (setq new-pos (string-match "[]*[;!'`\"$\\& \t{} |()<>]" arg pos))
450         (push (substring arg pos new-pos) accum)
451         (push "\\" accum)
452         (push (list (aref arg new-pos)) accum)
453         (setq pos (1+ new-pos)))
454       (if (= pos 0)
455           arg
456         (apply 'concat (nconc (nreverse accum) (list (substring arg pos))))))))
457
458 (defun mm-auto-mode-alist ()
459   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
460   (let ((alist auto-mode-alist)
461         out)
462     (while alist
463       (when (listp (cdar alist))
464         (push (car alist) out))
465       (pop alist))
466     (nreverse out)))
467
468 (defvar mm-inhibit-file-name-handlers
469   '(jka-compr-handler)
470   "A list of handlers doing (un)compression (etc) thingies.")
471
472 (defun mm-insert-file-contents (filename &optional visit beg end replace
473                                          inhibit)
474   "Like `insert-file-contents', q.v., but only reads in the file.
475 A buffer may be modified in several ways after reading into the buffer due
476 to advanced Emacs features, such as file-name-handlers, format decoding,
477 find-file-hooks, etc.
478 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers.
479   This function ensures that none of these modifications will take place."
480   (let ((format-alist nil)
481         (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
482         (default-major-mode 'fundamental-mode)
483         (enable-local-variables nil)
484         (after-insert-file-functions nil)
485         (enable-local-eval nil)
486         (find-file-hooks nil)
487         (inhibit-file-name-operation (if inhibit 
488                                          'insert-file-contents
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     (insert-file-contents filename visit beg end replace)))
496
497 (defun mm-append-to-file (start end filename &optional codesys inhibit)
498   "Append the contents of the region to the end of file FILENAME.
499 When called from a function, expects three arguments,
500 START, END and FILENAME.  START and END are buffer positions
501 saying what text to write.
502 Optional fourth argument specifies the coding system to use when
503 encoding the file.
504 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers."
505   (let ((coding-system-for-write 
506          (or codesys mm-text-coding-system-for-write 
507              mm-text-coding-system))
508         (inhibit-file-name-operation (if inhibit 
509                                          'append-to-file
510                                        inhibit-file-name-operation))
511         (inhibit-file-name-handlers
512          (if inhibit
513              (append mm-inhibit-file-name-handlers 
514                      inhibit-file-name-handlers)
515            inhibit-file-name-handlers)))
516     (append-to-file start end filename)))
517
518 (defun mm-write-region (start end filename &optional append visit lockname 
519                               coding-system inhibit)
520
521   "Like `write-region'.
522 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers."
523   (let ((coding-system-for-write 
524          (or coding-system mm-text-coding-system-for-write 
525              mm-text-coding-system))
526         (inhibit-file-name-operation (if inhibit 
527                                          'write-region
528                                        inhibit-file-name-operation))
529         (inhibit-file-name-handlers
530          (if inhibit
531              (append mm-inhibit-file-name-handlers 
532                      inhibit-file-name-handlers)
533            inhibit-file-name-handlers)))
534     (write-region start end filename append visit lockname)))
535
536 (provide 'mm-util)
537
538 ;;; mm-util.el ends here