Synch with 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 (defun mm-preferred-coding-system (charset)
233   ;; A typo in some Emacs versions.
234   (or (get-charset-property charset 'prefered-coding-system)
235       (get-charset-property charset 'preferred-coding-system)))
236
237 (defun mm-charset-after (&optional pos)
238   "Return charset of a character in current buffer at position POS.
239 If POS is nil, it defauls to the current point.
240 If POS is out of range, the value is nil.
241 If the charset is `composition', return the actual one."
242   (let ((charset (cond 
243                   ((fboundp 'charset-after)
244                    (charset-after pos))
245                   ((fboundp 'char-charset)
246                    (char-charset (char-after pos)))
247                   ((< (mm-char-int (char-after pos)) 128)
248                    'ascii)
249                   (mail-parse-mule-charset ;; cached mule-charset
250                    mail-parse-mule-charset)
251                   ((boundp 'current-language-environment)
252                    (let ((entry (assoc current-language-environment 
253                                        language-info-alist)))
254                      (setq mail-parse-mule-charset
255                            (or (car (last (assq 'charset entry)))
256                                'latin-iso8859-1))))
257                   (t                       ;; figure out the charset
258                    (setq mail-parse-mule-charset
259                          (or (car (last (assq mail-parse-charset
260                                               mm-mime-mule-charset-alist)))
261                              'latin-iso8859-1))))))
262     (if (eq charset 'composition)
263         (let ((p (or pos (point))))
264           (cadr (find-charset-region p (1+ p))))
265       charset)))
266
267 (defun mm-mime-charset (charset)
268   "Return the MIME charset corresponding to the MULE CHARSET."
269   (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
270       ;; This exists in Emacs 20.
271       (or
272        (and (mm-preferred-coding-system charset)
273             (coding-system-get
274              (mm-preferred-coding-system charset) 'mime-charset))
275        (and (eq charset 'ascii)
276             'us-ascii)
277        (mm-preferred-coding-system charset)
278        (mm-mule-charset-to-mime-charset charset))
279     ;; This is for XEmacs.
280     (mm-mule-charset-to-mime-charset charset)))
281
282 (defun mm-delete-duplicates (list)
283   "Simple  substitute for CL `delete-duplicates', testing with `equal'."
284   (let (result head)
285     (while list
286       (setq head (car list))
287       (setq list (delete head list))
288       (setq result (cons head result)))
289     (nreverse result)))
290
291 (defun mm-find-mime-charset-region (b e)
292   "Return the MIME charsets needed to encode the region between B and E."
293   (let ((charsets (mapcar 'mm-mime-charset
294                           (delq 'ascii
295                                 (mm-find-charset-region b e)))))
296     (when (memq 'iso-2022-jp-2 charsets)
297       (setq charsets (delq 'iso-2022-jp charsets)))
298     (setq charsets (mm-delete-duplicates charsets))
299     (if (and (> (length charsets) 1)
300              (fboundp 'find-coding-systems-region)
301              (memq 'utf-8 (find-coding-systems-region b e)))
302         '(utf-8)
303       charsets)))
304
305 (defsubst mm-multibyte-p ()
306   "Say whether multibyte is enabled."
307   (or (featurep 'xemacs)
308       (and (boundp 'enable-multibyte-characters)
309            enable-multibyte-characters)))
310
311 (defmacro mm-with-unibyte-buffer (&rest forms)
312   "Create a temporary buffer, and evaluate FORMS there like `progn'.
313 See also `with-temp-file' and `with-output-to-string'."
314   (let ((temp-buffer (make-symbol "temp-buffer"))
315         (multibyte (make-symbol "multibyte")))
316     `(if (or (string-match "XEmacs\\|Lucid" emacs-version)
317              (not (boundp 'enable-multibyte-characters)))
318          (with-temp-buffer ,@forms)
319        (let ((,multibyte (default-value 'enable-multibyte-characters))
320              ,temp-buffer)
321          (unwind-protect
322              (progn
323                (setq-default enable-multibyte-characters nil)
324                (setq ,temp-buffer
325                      (get-buffer-create (generate-new-buffer-name " *temp*")))
326                (unwind-protect
327                    (with-current-buffer ,temp-buffer
328                      (let ((buffer-file-coding-system mm-binary-coding-system)
329                            (coding-system-for-read mm-binary-coding-system)
330                            (coding-system-for-write mm-binary-coding-system))
331                        ,@forms))
332                  (and (buffer-name ,temp-buffer)
333                       (kill-buffer ,temp-buffer))))
334            (setq-default enable-multibyte-characters ,multibyte))))))
335 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
336 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
337
338 (defmacro mm-with-unibyte-current-buffer (&rest forms)
339   "Evaluate FORMS there like `progn' in current buffer."
340   (let ((multibyte (make-symbol "multibyte")))
341     `(if (or (featurep 'xemacs)
342              (not (fboundp 'set-buffer-multibyte)))
343          (progn
344            ,@forms)
345        (let ((,multibyte (default-value 'enable-multibyte-characters)))
346          (unwind-protect
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                (set-buffer-multibyte nil)
351                (setq-default enable-multibyte-characters nil)
352                ,@forms)
353            (setq-default enable-multibyte-characters ,multibyte)
354            (set-buffer-multibyte ,multibyte))))))
355 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
356 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
357
358 (defmacro mm-with-unibyte (&rest forms)
359   "Set default `enable-multibyte-characters' to `nil', eval the FORMS."
360   (let ((multibyte (make-symbol "multibyte")))
361     `(if (or (featurep 'xemacs)
362              (not (boundp 'enable-multibyte-characters)))
363          (progn ,@forms)
364        (let ((,multibyte (default-value 'enable-multibyte-characters)))
365          (unwind-protect
366              (progn
367                (setq-default enable-multibyte-characters nil)
368                ,@forms)
369            (setq-default enable-multibyte-characters ,multibyte))))))
370 (put 'mm-with-unibyte 'lisp-indent-function 0)
371 (put 'mm-with-unibyte 'edebug-form-spec '(body))
372
373 (defun mm-find-charset-region (b e)
374   "Return a list of charsets in the region."
375   (cond
376    ((and (mm-multibyte-p)
377          (fboundp 'find-charset-region))
378     ;; Remove composition since the base charsets have been included.
379     (delq 'composition (find-charset-region b e)))
380    ((not (boundp 'current-language-environment))
381     (save-excursion
382       (save-restriction
383         (narrow-to-region b e)
384         (goto-char (point-min))
385         (skip-chars-forward "\0-\177")
386         (if (eobp)
387             '(ascii)
388           (delq nil (list 'ascii 
389                           (or (car (last (assq mail-parse-charset
390                                                mm-mime-mule-charset-alist)))
391                               'latin-iso8859-1)))))))
392    (t
393     ;; We are in a unibyte buffer, so we futz around a bit.
394     (save-excursion
395       (save-restriction
396         (narrow-to-region b e)
397         (goto-char (point-min))
398         (let ((entry (assoc current-language-environment 
399                             language-info-alist)))
400           (skip-chars-forward "\0-\177")
401           (if (eobp)
402               '(ascii)
403             (delq nil (list 'ascii 
404                             (or (car (last (assq 'charset entry)))
405                                 'latin-iso8859-1))))))))))
406
407 (static-if (fboundp 'shell-quote-argument)
408     (defalias 'mm-quote-arg 'shell-quote-argument)
409   (defun mm-quote-arg (arg)
410     "Return a version of ARG that is safe to evaluate in a shell."
411     (let ((pos 0) new-pos accum)
412       ;; *** bug: we don't handle newline characters properly
413       (while (setq new-pos (string-match "[]*[;!'`\"$\\& \t{} |()<>]" arg pos))
414         (push (substring arg pos new-pos) accum)
415         (push "\\" accum)
416         (push (list (aref arg new-pos)) accum)
417         (setq pos (1+ new-pos)))
418       (if (= pos 0)
419           arg
420         (apply 'concat (nconc (nreverse accum) (list (substring arg pos))))))))
421
422 (defun mm-auto-mode-alist ()
423   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
424   (let ((alist auto-mode-alist)
425         out)
426     (while alist
427       (when (listp (cdar alist))
428         (push (car alist) out))
429       (pop alist))
430     (nreverse out)))
431
432 (defvar mm-inhibit-file-name-handlers
433   '(jka-compr-handler)
434   "A list of handlers doing (un)compression (etc) thingies.")
435
436 (defun mm-insert-file-contents (filename &optional visit beg end replace
437                                          inhibit)
438   "Like `insert-file-contents', q.v., but only reads in the file.
439 A buffer may be modified in several ways after reading into the buffer due
440 to advanced Emacs features, such as file-name-handlers, format decoding,
441 find-file-hooks, etc.
442 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers.
443   This function ensures that none of these modifications will take place."
444   (let ((format-alist nil)
445         (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
446         (default-major-mode 'fundamental-mode)
447         (enable-local-variables nil)
448         (after-insert-file-functions nil)
449         (enable-local-eval nil)
450         (find-file-hooks nil)
451         (inhibit-file-name-operation (if inhibit 
452                                          'insert-file-contents
453                                        inhibit-file-name-operation))
454         (inhibit-file-name-handlers
455          (if inhibit
456              (append mm-inhibit-file-name-handlers 
457                      inhibit-file-name-handlers)
458            inhibit-file-name-handlers)))
459     (insert-file-contents filename visit beg end replace)))
460
461 (defun mm-append-to-file (start end filename &optional codesys inhibit)
462   "Append the contents of the region to the end of file FILENAME.
463 When called from a function, expects three arguments,
464 START, END and FILENAME.  START and END are buffer positions
465 saying what text to write.
466 Optional fourth argument specifies the coding system to use when
467 encoding the file.
468 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers."
469   (let ((coding-system-for-write 
470          (or codesys mm-text-coding-system-for-write 
471              mm-text-coding-system))
472         (inhibit-file-name-operation (if inhibit 
473                                          'append-to-file
474                                        inhibit-file-name-operation))
475         (inhibit-file-name-handlers
476          (if inhibit
477              (append mm-inhibit-file-name-handlers 
478                      inhibit-file-name-handlers)
479            inhibit-file-name-handlers)))
480     (append-to-file start end filename)))
481
482 (defun mm-write-region (start end filename &optional append visit lockname 
483                               coding-system inhibit)
484
485   "Like `write-region'.
486 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers."
487   (let ((coding-system-for-write 
488          (or coding-system mm-text-coding-system-for-write 
489              mm-text-coding-system))
490         (inhibit-file-name-operation (if inhibit 
491                                          'write-region
492                                        inhibit-file-name-operation))
493         (inhibit-file-name-handlers
494          (if inhibit
495              (append mm-inhibit-file-name-handlers 
496                      inhibit-file-name-handlers)
497            inhibit-file-name-handlers)))
498     (write-region start end filename append visit lockname)))
499
500 (provide 'mm-util)
501
502 ;;; mm-util.el ends here