2000-11-08 08:38:30 ShengHuo ZHU <zsh@cs.rochester.edu>
[gnus] / 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 'cl))
28 (require 'mail-prsvr)
29
30 (defvar mm-mime-mule-charset-alist
31   '((us-ascii ascii)
32     (iso-8859-1 latin-iso8859-1)
33     (iso-8859-2 latin-iso8859-2)
34     (iso-8859-3 latin-iso8859-3)
35     (iso-8859-4 latin-iso8859-4)
36     (iso-8859-5 cyrillic-iso8859-5)
37     ;; Non-mule (X)Emacs uses the last mule-charset for 8bit characters.
38     ;; The fake mule-charset, gnus-koi8-r, tells Gnus that the default 
39     ;; charset is koi8-r, not iso-8859-5.
40     (koi8-r cyrillic-iso8859-5 gnus-koi8-r)
41     (iso-8859-6 arabic-iso8859-6)
42     (iso-8859-7 greek-iso8859-7)
43     (iso-8859-8 hebrew-iso8859-8)
44     (iso-8859-9 latin-iso8859-9)
45     (viscii vietnamese-viscii-lower)
46     (iso-2022-jp latin-jisx0201 japanese-jisx0208 japanese-jisx0208-1978)
47     (euc-kr korean-ksc5601)
48     (cn-gb-2312 chinese-gb2312)
49     (cn-big5 chinese-big5-1 chinese-big5-2)
50     (tibetan tibetan)
51     (thai-tis620 thai-tis620)
52     (iso-2022-7bit ethiopic arabic-1-column arabic-2-column)
53     (iso-2022-jp-2 latin-iso8859-1 greek-iso8859-7
54                    latin-jisx0201 japanese-jisx0208-1978
55                    chinese-gb2312 japanese-jisx0208
56                    korean-ksc5601 japanese-jisx0212
57                    katakana-jisx0201)
58     (iso-2022-int-1 latin-iso8859-1 greek-iso8859-7
59                     latin-jisx0201 japanese-jisx0208-1978
60                     chinese-gb2312 japanese-jisx0208
61                     korean-ksc5601 japanese-jisx0212
62                     chinese-cns11643-1 chinese-cns11643-2)
63     (iso-2022-int-1 latin-iso8859-1 latin-iso8859-2
64                     cyrillic-iso8859-5 greek-iso8859-7
65                     latin-jisx0201 japanese-jisx0208-1978
66                     chinese-gb2312 japanese-jisx0208
67                     korean-ksc5601 japanese-jisx0212
68                     chinese-cns11643-1 chinese-cns11643-2
69                     chinese-cns11643-3 chinese-cns11643-4
70                     chinese-cns11643-5 chinese-cns11643-6
71                     chinese-cns11643-7)
72     (utf-8 unicode-a unicode-b unicode-c unicode-d unicode-e))
73   "Alist of MIME-charset/MULE-charsets.")
74
75 (eval-and-compile
76   (mapcar
77    (lambda (elem)
78      (let ((nfunc (intern (format "mm-%s" (car elem)))))
79        (if (fboundp (car elem))
80            (defalias nfunc (car elem))
81          (defalias nfunc (cdr elem)))))
82    '((decode-coding-string . (lambda (s a) s))
83      (encode-coding-string . (lambda (s a) s))
84      (encode-coding-region . ignore)
85      (coding-system-list . ignore)
86      (decode-coding-region . ignore)
87      (char-int . identity)
88      (device-type . ignore)
89      (coding-system-equal . equal)
90      (annotationp . ignore)
91      (set-buffer-file-coding-system . ignore)
92      (make-char
93       . (lambda (charset int)
94           (int-to-char int)))
95      (read-coding-system
96       . (lambda (prompt)
97           "Prompt the user for a coding system."
98           (completing-read
99            prompt (mapcar (lambda (s) (list (symbol-name (car s))))
100                           mm-mime-mule-charset-alist))))
101      (read-charset
102       . (lambda (prompt)
103           "Return a charset."
104           (intern
105            (completing-read
106             prompt
107             (mapcar (lambda (e) (list (symbol-name (car e))))
108                     mm-mime-mule-charset-alist)
109             nil t))))
110      (subst-char-in-string
111       . (lambda (from to string) ;; stolen (and renamed) from nnheader.el
112           "Replace characters in STRING from FROM to TO."
113           (let ((string (substring string 0))   ;Copy string.
114                 (len (length string))
115                 (idx 0))
116             ;; Replace all occurrences of FROM with TO.
117             (while (< idx len)
118               (when (= (aref string idx) from)
119                 (aset string idx to))
120               (setq idx (1+ idx)))
121             string)))
122       )))
123
124 (eval-and-compile
125   (defalias 'mm-char-or-char-int-p
126     (cond 
127      ((fboundp 'char-or-char-int-p) 'char-or-char-int-p)
128      ((fboundp 'char-valid-p) 'char-valid-p) 
129      (t 'identity))))
130
131 (defvar mm-coding-system-list nil)
132 (defun mm-get-coding-system-list ()
133   "Get the coding system list."
134   (or mm-coding-system-list
135       (setq mm-coding-system-list (mm-coding-system-list))))
136
137 (defvar mm-charset-synonym-alist
138   '((big5 . cn-big5)
139     (gb2312 . cn-gb-2312)
140     (x-ctext . ctext))
141   "A mapping from invalid charset names to the real charset names.")
142
143 (defun mm-coding-system-p (sym)
144   "Return non-nil if SYM is a coding system."
145   (or (and (fboundp 'coding-system-p) (coding-system-p sym))
146       (memq sym (mm-get-coding-system-list))))
147
148 (defvar mm-binary-coding-system
149   (cond 
150    ((mm-coding-system-p 'binary) 'binary)
151    ((mm-coding-system-p 'no-conversion) 'no-conversion)
152    (t nil))
153   "100% binary coding system.")
154
155 (defvar mm-text-coding-system
156   (or (if (memq system-type '(windows-nt ms-dos ms-windows))
157           (and (mm-coding-system-p 'raw-text-dos) 'raw-text-dos)
158         (and (mm-coding-system-p 'raw-text) 'raw-text))
159       mm-binary-coding-system)
160   "Text-safe coding system (For removing ^M).")
161
162 (defvar mm-text-coding-system-for-write nil
163   "Text coding system for write.")
164
165 (defvar mm-auto-save-coding-system
166   (cond 
167    ((mm-coding-system-p 'emacs-mule)
168     (if (memq system-type '(windows-nt ms-dos ms-windows))
169         (if (mm-coding-system-p 'emacs-mule-dos) 
170             'emacs-mule-dos mm-binary-coding-system)
171       'emacs-mule))
172    ((mm-coding-system-p 'escape-quoted) 'escape-quoted)
173    (t mm-binary-coding-system))
174   "Coding system of auto save file.")
175
176 ;;; Internal variables:
177
178 ;;; Functions:
179
180 (defun mm-mule-charset-to-mime-charset (charset)
181   "Return the MIME charset corresponding to MULE CHARSET."
182   (let ((alist mm-mime-mule-charset-alist)
183         out)
184     (while alist
185       (when (memq charset (cdar alist))
186         (setq out (caar alist)
187               alist nil))
188       (pop alist))
189     out))
190
191 (defun mm-charset-to-coding-system (charset &optional lbt)
192   "Return coding-system corresponding to CHARSET.
193 CHARSET is a symbol naming a MIME charset.
194 If optional argument LBT (`unix', `dos' or `mac') is specified, it is
195 used as the line break code type of the coding system."
196   (when (stringp charset)
197     (setq charset (intern (downcase charset))))
198   (setq charset
199         (or (cdr (assq charset mm-charset-synonym-alist))
200             charset))
201   (when lbt
202     (setq charset (intern (format "%s-%s" charset lbt))))
203   (cond
204    ;; Running in a non-MULE environment.
205    ((null (mm-get-coding-system-list))
206     charset)
207    ;; ascii
208    ((eq charset 'us-ascii)
209     'ascii)
210    ;; Check to see whether we can handle this charset.
211    ((memq charset (mm-get-coding-system-list))
212     charset)
213    ;; Nope.
214    (t
215     nil)))
216
217 (defsubst mm-replace-chars-in-string (string from to)
218   (mm-subst-char-in-string from to 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 (and (not (featurep 'xemacs))
327            (boundp 'enable-multibyte-characters))
328       enable-multibyte-characters
329     (featurep 'mule)))
330
331 (defmacro mm-with-unibyte-buffer (&rest forms)
332   "Create a temporary buffer, and evaluate FORMS there like `progn'.
333 See also `with-temp-file' and `with-output-to-string'."
334   (let ((temp-buffer (make-symbol "temp-buffer"))
335         (multibyte (make-symbol "multibyte")))
336     `(if (or (featurep 'xemacs)
337              (not (boundp 'enable-multibyte-characters)))
338          (with-temp-buffer ,@forms)
339        (let ((,multibyte (default-value 'enable-multibyte-characters))
340              ,temp-buffer)
341          (unwind-protect
342              (progn
343                (setq-default enable-multibyte-characters nil)
344                (setq ,temp-buffer
345                      (get-buffer-create (generate-new-buffer-name " *temp*")))
346                (unwind-protect
347                    (with-current-buffer ,temp-buffer
348                      (let ((buffer-file-coding-system mm-binary-coding-system)
349                            (coding-system-for-read mm-binary-coding-system)
350                            (coding-system-for-write mm-binary-coding-system))
351                        ,@forms))
352                  (and (buffer-name ,temp-buffer)
353                       (kill-buffer ,temp-buffer))))
354            (setq-default enable-multibyte-characters ,multibyte))))))
355 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
356 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
357
358 (defmacro mm-with-unibyte-current-buffer (&rest forms)
359   "Evaluate FORMS there like `progn' in current buffer."
360   (let ((multibyte (make-symbol "multibyte")))
361     `(if (or (featurep 'xemacs)
362              (not (fboundp 'set-buffer-multibyte)))
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-current-buffer-mule4 (&rest forms)
379   "Evaluate FORMS there like `progn' in current buffer.
380 Mule4 only."
381   (let ((multibyte (make-symbol "multibyte")))
382     `(if (or (featurep 'xemacs)
383              (not (fboundp 'set-buffer-multibyte))
384              (charsetp 'eight-bit-control)) ;; For Emacs Mule 4 only.
385          (progn
386            ,@forms)
387        (let ((,multibyte (default-value 'enable-multibyte-characters)))
388          (unwind-protect
389              (let ((buffer-file-coding-system mm-binary-coding-system)
390                    (coding-system-for-read mm-binary-coding-system)
391                    (coding-system-for-write mm-binary-coding-system))
392                (set-buffer-multibyte nil)
393                (setq-default enable-multibyte-characters nil)
394                ,@forms)
395            (setq-default enable-multibyte-characters ,multibyte)
396            (set-buffer-multibyte ,multibyte))))))
397 (put 'mm-with-unibyte-current-buffer-mule4 'lisp-indent-function 0)
398 (put 'mm-with-unibyte-current-buffer-mule4 'edebug-form-spec '(body))
399
400 (defmacro mm-with-unibyte (&rest forms)
401   "Set default `enable-multibyte-characters' to `nil', eval the FORMS."
402   (let ((multibyte (make-symbol "multibyte")))
403     `(if (or (featurep 'xemacs)
404              (not (boundp 'enable-multibyte-characters)))
405          (progn ,@forms)
406        (let ((,multibyte (default-value 'enable-multibyte-characters)))
407          (unwind-protect
408              (progn
409                (setq-default enable-multibyte-characters nil)
410                ,@forms)
411            (setq-default enable-multibyte-characters ,multibyte))))))
412 (put 'mm-with-unibyte 'lisp-indent-function 0)
413 (put 'mm-with-unibyte 'edebug-form-spec '(body))
414
415 (defun mm-find-charset-region (b e)
416   "Return a list of charsets in the region."
417   (cond
418    ((and (mm-multibyte-p)
419          (fboundp 'find-charset-region))
420     ;; Remove composition since the base charsets have been included.
421     (delq 'composition (find-charset-region b e)))
422    (t
423     ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
424     (save-excursion
425       (save-restriction
426         (narrow-to-region b e)
427         (goto-char (point-min))
428         (skip-chars-forward "\0-\177")
429         (if (eobp)
430             '(ascii)
431           (let (charset)
432             (setq charset
433                   (and (boundp 'current-language-environment)
434                        (car (last (assq 'charset 
435                                         (assoc current-language-environment 
436                                                language-info-alist))))))
437             (if (eq charset 'ascii) (setq charset nil))
438             (or charset
439                 (setq charset
440                       (car (last (assq mail-parse-charset
441                                        mm-mime-mule-charset-alist)))))
442             (list 'ascii (or charset 'latin-iso8859-1)))))))))
443
444 (if (fboundp 'shell-quote-argument)
445     (defalias 'mm-quote-arg 'shell-quote-argument)
446   (defun mm-quote-arg (arg)
447     "Return a version of ARG that is safe to evaluate in a shell."
448     (let ((pos 0) new-pos accum)
449       ;; *** bug: we don't handle newline characters properly
450       (while (setq new-pos (string-match "[]*[;!'`\"$\\& \t{} |()<>]" arg pos))
451         (push (substring arg pos new-pos) accum)
452         (push "\\" accum)
453         (push (list (aref arg new-pos)) accum)
454         (setq pos (1+ new-pos)))
455       (if (= pos 0)
456           arg
457         (apply 'concat (nconc (nreverse accum) (list (substring arg pos))))))))
458
459 (defun mm-auto-mode-alist ()
460   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
461   (let ((alist auto-mode-alist)
462         out)
463     (while alist
464       (when (listp (cdar alist))
465         (push (car alist) out))
466       (pop alist))
467     (nreverse out)))
468
469 (defvar mm-inhibit-file-name-handlers
470   '(jka-compr-handler)
471   "A list of handlers doing (un)compression (etc) thingies.")
472
473 (defun mm-insert-file-contents (filename &optional visit beg end replace
474                                          inhibit)
475   "Like `insert-file-contents', q.v., but only reads in the file.
476 A buffer may be modified in several ways after reading into the buffer due
477 to advanced Emacs features, such as file-name-handlers, format decoding,
478 find-file-hooks, etc.
479 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers.
480   This function ensures that none of these modifications will take place."
481   (let ((format-alist nil)
482         (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
483         (default-major-mode 'fundamental-mode)
484         (enable-local-variables nil)
485         (after-insert-file-functions nil)
486         (enable-local-eval nil)
487         (find-file-hooks nil)
488         (inhibit-file-name-operation (if inhibit 
489                                          'insert-file-contents
490                                        inhibit-file-name-operation))
491         (inhibit-file-name-handlers
492          (if inhibit
493              (append mm-inhibit-file-name-handlers 
494                      inhibit-file-name-handlers)
495            inhibit-file-name-handlers)))
496     (insert-file-contents filename visit beg end replace)))
497
498 (defun mm-append-to-file (start end filename &optional codesys inhibit)
499   "Append the contents of the region to the end of file FILENAME.
500 When called from a function, expects three arguments,
501 START, END and FILENAME.  START and END are buffer positions
502 saying what text to write.
503 Optional fourth argument specifies the coding system to use when
504 encoding the file.
505 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers."
506   (let ((coding-system-for-write 
507          (or codesys mm-text-coding-system-for-write 
508              mm-text-coding-system))
509         (inhibit-file-name-operation (if inhibit 
510                                          'append-to-file
511                                        inhibit-file-name-operation))
512         (inhibit-file-name-handlers
513          (if inhibit
514              (append mm-inhibit-file-name-handlers 
515                      inhibit-file-name-handlers)
516            inhibit-file-name-handlers)))
517     (append-to-file start end filename)))
518
519 (defun mm-write-region (start end filename &optional append visit lockname 
520                               coding-system inhibit)
521
522   "Like `write-region'.
523 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers."
524   (let ((coding-system-for-write 
525          (or coding-system mm-text-coding-system-for-write 
526              mm-text-coding-system))
527         (inhibit-file-name-operation (if inhibit 
528                                          'write-region
529                                        inhibit-file-name-operation))
530         (inhibit-file-name-handlers
531          (if inhibit
532              (append mm-inhibit-file-name-handlers 
533                      inhibit-file-name-handlers)
534            inhibit-file-name-handlers)))
535     (write-region start end filename append visit lockname)))
536
537 (provide 'mm-util)
538
539 ;;; mm-util.el ends here