2000-12-17 10:00:00 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     (cn-gb . cn-gb-2312)
141     (x-ctext . ctext))
142   "A mapping from invalid charset names to the real charset names.")
143
144 (defun mm-coding-system-p (sym)
145   "Return non-nil if SYM is a coding system."
146   (or (and (fboundp 'coding-system-p) (coding-system-p sym))
147       (memq sym (mm-get-coding-system-list))))
148
149 (defvar mm-binary-coding-system
150   (cond 
151    ((mm-coding-system-p 'binary) 'binary)
152    ((mm-coding-system-p 'no-conversion) 'no-conversion)
153    (t nil))
154   "100% binary coding system.")
155
156 (defvar mm-text-coding-system
157   (or (if (memq system-type '(windows-nt ms-dos ms-windows))
158           (and (mm-coding-system-p 'raw-text-dos) 'raw-text-dos)
159         (and (mm-coding-system-p 'raw-text) 'raw-text))
160       mm-binary-coding-system)
161   "Text-safe coding system (For removing ^M).")
162
163 (defvar mm-text-coding-system-for-write nil
164   "Text coding system for write.")
165
166 (defvar mm-auto-save-coding-system
167   (cond 
168    ((mm-coding-system-p 'emacs-mule)
169     (if (memq system-type '(windows-nt ms-dos ms-windows))
170         (if (mm-coding-system-p 'emacs-mule-dos) 
171             'emacs-mule-dos mm-binary-coding-system)
172       'emacs-mule))
173    ((mm-coding-system-p 'escape-quoted) 'escape-quoted)
174    (t mm-binary-coding-system))
175   "Coding system of auto save file.")
176
177 ;;; Internal variables:
178
179 ;;; Functions:
180
181 (defun mm-mule-charset-to-mime-charset (charset)
182   "Return the MIME charset corresponding to MULE CHARSET."
183   (let ((alist mm-mime-mule-charset-alist)
184         out)
185     (while alist
186       (when (memq charset (cdar alist))
187         (setq out (caar alist)
188               alist nil))
189       (pop alist))
190     out))
191
192 (defun mm-charset-to-coding-system (charset &optional lbt)
193   "Return coding-system corresponding to CHARSET.
194 CHARSET is a symbol naming a MIME charset.
195 If optional argument LBT (`unix', `dos' or `mac') is specified, it is
196 used as the line break code type of the coding system."
197   (when (stringp charset)
198     (setq charset (intern (downcase charset))))
199   (setq charset
200         (or (cdr (assq charset mm-charset-synonym-alist))
201             charset))
202   (when lbt
203     (setq charset (intern (format "%s-%s" charset lbt))))
204   (cond
205    ;; Running in a non-MULE environment.
206    ((null (mm-get-coding-system-list))
207     charset)
208    ;; ascii
209    ((eq charset 'us-ascii)
210     'ascii)
211    ;; Check to see whether we can handle this charset.
212    ((memq charset (mm-get-coding-system-list))
213     charset)
214    ;; Nope.
215    (t
216     nil)))
217
218 (defsubst mm-replace-chars-in-string (string from to)
219   (mm-subst-char-in-string from to string))
220
221 (defsubst mm-enable-multibyte ()
222   "Enable multibyte in the current buffer."
223   (when (and (fboundp 'set-buffer-multibyte)
224              (boundp 'enable-multibyte-characters)
225              (default-value 'enable-multibyte-characters))
226     (set-buffer-multibyte t)))
227
228 (defsubst mm-disable-multibyte ()
229   "Disable multibyte in the current buffer."
230   (when (fboundp 'set-buffer-multibyte)
231     (set-buffer-multibyte nil)))
232
233 (defsubst mm-enable-multibyte-mule4 ()
234   "Enable multibyte in the current buffer.
235 Only used in Emacs Mule 4."
236   (when (and (fboundp 'set-buffer-multibyte)
237              (boundp 'enable-multibyte-characters)
238              (default-value 'enable-multibyte-characters)
239              (fboundp 'charsetp)
240              (not (charsetp 'eight-bit-control)))
241     (set-buffer-multibyte t)))
242
243 (defsubst mm-disable-multibyte-mule4 ()
244   "Disable multibyte in the current buffer.
245 Only used in Emacs Mule 4."
246   (when (and (fboundp 'set-buffer-multibyte)
247              (fboundp 'charsetp)
248              (not (charsetp 'eight-bit-control)))
249     (set-buffer-multibyte nil)))
250
251 (defun mm-preferred-coding-system (charset)
252   ;; A typo in some Emacs versions.
253   (or (get-charset-property charset 'prefered-coding-system)
254       (get-charset-property charset 'preferred-coding-system)))
255
256 (defun mm-charset-after (&optional pos)
257   "Return charset of a character in current buffer at position POS.
258 If POS is nil, it defauls to the current point.
259 If POS is out of range, the value is nil.
260 If the charset is `composition', return the actual one."
261   (let ((char (char-after pos)) charset)
262     (if (< (mm-char-int char) 128)
263         (setq charset 'ascii)
264       ;; charset-after is fake in some Emacsen.
265       (setq charset (and (fboundp 'char-charset) (char-charset char)))
266       (if (eq charset 'composition)
267           (let ((p (or pos (point))))
268             (cadr (find-charset-region p (1+ p))))
269         (if (and charset (not (memq charset '(ascii eight-bit-control
270                                                     eight-bit-graphic))))
271             charset
272           (or
273            mail-parse-mule-charset ;; cached mule-charset
274            (progn
275              (setq mail-parse-mule-charset
276                    (and (boundp 'current-language-environment)
277                       (car (last 
278                             (assq 'charset 
279                                   (assoc current-language-environment 
280                                          language-info-alist))))))
281              (if (or (not mail-parse-mule-charset)
282                      (eq mail-parse-mule-charset 'ascii))
283                  (setq mail-parse-mule-charset
284                        (or (car (last (assq mail-parse-charset
285                                             mm-mime-mule-charset-alist)))
286                            'latin-iso8859-1)))
287              mail-parse-mule-charset)))))))
288
289 (defun mm-mime-charset (charset)
290   "Return the MIME charset corresponding to the MULE CHARSET."
291   (if (eq charset 'unknown)
292       (error "8-bit characters are found in the message, please specify charset."))
293   (if (and (fboundp 'coding-system-get) (fboundp 'get-charset-property))
294       ;; This exists in Emacs 20.
295       (or
296        (and (mm-preferred-coding-system charset)
297             (coding-system-get
298              (mm-preferred-coding-system charset) 'mime-charset))
299        (and (eq charset 'ascii)
300             'us-ascii)
301        (mm-preferred-coding-system charset)
302        (mm-mule-charset-to-mime-charset charset))
303     ;; This is for XEmacs.
304     (mm-mule-charset-to-mime-charset charset)))
305
306 (defun mm-delete-duplicates (list)
307   "Simple  substitute for CL `delete-duplicates', testing with `equal'."
308   (let (result head)
309     (while list
310       (setq head (car list))
311       (setq list (delete head list))
312       (setq result (cons head result)))
313     (nreverse result)))
314
315 (defun mm-find-mime-charset-region (b e)
316   "Return the MIME charsets needed to encode the region between B and E."
317   (let ((charsets (mapcar 'mm-mime-charset
318                           (delq 'ascii
319                                 (mm-find-charset-region b e)))))
320     (when (memq 'iso-2022-jp-2 charsets)
321       (setq charsets (delq 'iso-2022-jp charsets)))
322     (setq charsets (mm-delete-duplicates charsets))
323     (if (and (> (length charsets) 1)
324              (fboundp 'find-coding-systems-region)
325              (memq 'utf-8 (find-coding-systems-region b e)))
326         '(utf-8)
327       charsets)))
328
329 (defsubst mm-multibyte-p ()
330   "Say whether multibyte is enabled."
331   (if (and (not (featurep 'xemacs))
332            (boundp 'enable-multibyte-characters))
333       enable-multibyte-characters
334     (featurep 'mule)))
335
336 (defmacro mm-with-unibyte-buffer (&rest forms)
337   "Create a temporary buffer, and evaluate FORMS there like `progn'.
338 See also `with-temp-file' and `with-output-to-string'."
339   (let ((temp-buffer (make-symbol "temp-buffer"))
340         (multibyte (make-symbol "multibyte")))
341     `(if (or (featurep 'xemacs)
342              (not (boundp 'enable-multibyte-characters)))
343          (with-temp-buffer ,@forms)
344        (let ((,multibyte (default-value 'enable-multibyte-characters))
345              ,temp-buffer)
346          (unwind-protect
347              (progn
348                (setq-default enable-multibyte-characters nil)
349                (setq ,temp-buffer
350                      (get-buffer-create (generate-new-buffer-name " *temp*")))
351                (unwind-protect
352                    (with-current-buffer ,temp-buffer
353                      (let ((buffer-file-coding-system mm-binary-coding-system)
354                            (coding-system-for-read mm-binary-coding-system)
355                            (coding-system-for-write mm-binary-coding-system))
356                        ,@forms))
357                  (and (buffer-name ,temp-buffer)
358                       (kill-buffer ,temp-buffer))))
359            (setq-default enable-multibyte-characters ,multibyte))))))
360 (put 'mm-with-unibyte-buffer 'lisp-indent-function 0)
361 (put 'mm-with-unibyte-buffer 'edebug-form-spec '(body))
362
363 (defmacro mm-with-unibyte-current-buffer (&rest forms)
364   "Evaluate FORMS there like `progn' in current buffer."
365   (let ((multibyte (make-symbol "multibyte")))
366     `(if (or (featurep 'xemacs)
367              (not (fboundp 'set-buffer-multibyte)))
368          (progn
369            ,@forms)
370        (let ((,multibyte (default-value 'enable-multibyte-characters)))
371          (unwind-protect
372              (let ((buffer-file-coding-system mm-binary-coding-system)
373                    (coding-system-for-read mm-binary-coding-system)
374                    (coding-system-for-write mm-binary-coding-system))
375                (set-buffer-multibyte nil)
376                (setq-default enable-multibyte-characters nil)
377                ,@forms)
378            (setq-default enable-multibyte-characters ,multibyte)
379            (set-buffer-multibyte ,multibyte))))))
380 (put 'mm-with-unibyte-current-buffer 'lisp-indent-function 0)
381 (put 'mm-with-unibyte-current-buffer 'edebug-form-spec '(body))
382
383 (defmacro mm-with-unibyte-current-buffer-mule4 (&rest forms)
384   "Evaluate FORMS there like `progn' in current buffer.
385 Mule4 only."
386   (let ((multibyte (make-symbol "multibyte")))
387     `(if (or (featurep 'xemacs)
388              (not (fboundp 'set-buffer-multibyte))
389              (not (fboundp 'charsetp))
390              (charsetp 'eight-bit-control)) ;; For Emacs Mule 4 only.
391          (progn
392            ,@forms)
393        (let ((,multibyte (default-value 'enable-multibyte-characters)))
394          (unwind-protect
395              (let ((buffer-file-coding-system mm-binary-coding-system)
396                    (coding-system-for-read mm-binary-coding-system)
397                    (coding-system-for-write mm-binary-coding-system))
398                (set-buffer-multibyte nil)
399                (setq-default enable-multibyte-characters nil)
400                ,@forms)
401            (setq-default enable-multibyte-characters ,multibyte)
402            (set-buffer-multibyte ,multibyte))))))
403 (put 'mm-with-unibyte-current-buffer-mule4 'lisp-indent-function 0)
404 (put 'mm-with-unibyte-current-buffer-mule4 'edebug-form-spec '(body))
405
406 (defmacro mm-with-unibyte (&rest forms)
407   "Set default `enable-multibyte-characters' to `nil', eval the FORMS."
408   (let ((multibyte (make-symbol "multibyte")))
409     `(if (or (featurep 'xemacs)
410              (not (boundp 'enable-multibyte-characters)))
411          (progn ,@forms)
412        (let ((,multibyte (default-value 'enable-multibyte-characters)))
413          (unwind-protect
414              (progn
415                (setq-default enable-multibyte-characters nil)
416                ,@forms)
417            (setq-default enable-multibyte-characters ,multibyte))))))
418 (put 'mm-with-unibyte 'lisp-indent-function 0)
419 (put 'mm-with-unibyte 'edebug-form-spec '(body))
420
421 (defun mm-find-charset-region (b e)
422   "Return a list of charsets in the region."
423   (cond
424    ((and (mm-multibyte-p)
425          (fboundp 'find-charset-region))
426     ;; Remove composition since the base charsets have been included.
427     ;; Remove eight-bit-*, treat them as ascii.
428     (let ((css (find-charset-region b e)))
429       (mapcar (lambda (cs) (setq css (delq cs css)))
430               '(composition eight-bit-control eight-bit-graphic))
431       css))
432    (t
433     ;; We are in a unibyte buffer or XEmacs non-mule, so we futz around a bit.
434     (save-excursion
435       (save-restriction
436         (narrow-to-region b e)
437         (goto-char (point-min))
438         (skip-chars-forward "\0-\177")
439         (if (eobp)
440             '(ascii)
441           (let (charset)
442             (setq charset
443                   (and (boundp 'current-language-environment)
444                        (car (last (assq 'charset 
445                                         (assoc current-language-environment 
446                                                language-info-alist))))))
447             (if (eq charset 'ascii) (setq charset nil))
448             (or charset
449                 (setq charset
450                       (car (last (assq mail-parse-charset
451                                        mm-mime-mule-charset-alist)))))
452             (list 'ascii (or charset 'latin-iso8859-1)))))))))
453
454 (if (fboundp 'shell-quote-argument)
455     (defalias 'mm-quote-arg 'shell-quote-argument)
456   (defun mm-quote-arg (arg)
457     "Return a version of ARG that is safe to evaluate in a shell."
458     (let ((pos 0) new-pos accum)
459       ;; *** bug: we don't handle newline characters properly
460       (while (setq new-pos (string-match "[]*[;!'`\"$\\& \t{} |()<>]" arg pos))
461         (push (substring arg pos new-pos) accum)
462         (push "\\" accum)
463         (push (list (aref arg new-pos)) accum)
464         (setq pos (1+ new-pos)))
465       (if (= pos 0)
466           arg
467         (apply 'concat (nconc (nreverse accum) (list (substring arg pos))))))))
468
469 (defun mm-auto-mode-alist ()
470   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
471   (let ((alist auto-mode-alist)
472         out)
473     (while alist
474       (when (listp (cdar alist))
475         (push (car alist) out))
476       (pop alist))
477     (nreverse out)))
478
479 (defvar mm-inhibit-file-name-handlers
480   '(jka-compr-handler)
481   "A list of handlers doing (un)compression (etc) thingies.")
482
483 (defun mm-insert-file-contents (filename &optional visit beg end replace
484                                          inhibit)
485   "Like `insert-file-contents', q.v., but only reads in the file.
486 A buffer may be modified in several ways after reading into the buffer due
487 to advanced Emacs features, such as file-name-handlers, format decoding,
488 find-file-hooks, etc.
489 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers.
490   This function ensures that none of these modifications will take place."
491   (let ((format-alist nil)
492         (auto-mode-alist (if inhibit nil (mm-auto-mode-alist)))
493         (default-major-mode 'fundamental-mode)
494         (enable-local-variables nil)
495         (after-insert-file-functions nil)
496         (enable-local-eval nil)
497         (find-file-hooks nil)
498         (inhibit-file-name-operation (if inhibit 
499                                          'insert-file-contents
500                                        inhibit-file-name-operation))
501         (inhibit-file-name-handlers
502          (if inhibit
503              (append mm-inhibit-file-name-handlers 
504                      inhibit-file-name-handlers)
505            inhibit-file-name-handlers)))
506     (insert-file-contents filename visit beg end replace)))
507
508 (defun mm-append-to-file (start end filename &optional codesys inhibit)
509   "Append the contents of the region to the end of file FILENAME.
510 When called from a function, expects three arguments,
511 START, END and FILENAME.  START and END are buffer positions
512 saying what text to write.
513 Optional fourth argument specifies the coding system to use when
514 encoding the file.
515 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers."
516   (let ((coding-system-for-write 
517          (or codesys mm-text-coding-system-for-write 
518              mm-text-coding-system))
519         (inhibit-file-name-operation (if inhibit 
520                                          'append-to-file
521                                        inhibit-file-name-operation))
522         (inhibit-file-name-handlers
523          (if inhibit
524              (append mm-inhibit-file-name-handlers 
525                      inhibit-file-name-handlers)
526            inhibit-file-name-handlers)))
527     (append-to-file start end filename)))
528
529 (defun mm-write-region (start end filename &optional append visit lockname 
530                               coding-system inhibit)
531
532   "Like `write-region'.
533 If INHIBIT is non-nil, inhibit mm-inhibit-file-name-handlers."
534   (let ((coding-system-for-write 
535          (or coding-system mm-text-coding-system-for-write 
536              mm-text-coding-system))
537         (inhibit-file-name-operation (if inhibit 
538                                          'write-region
539                                        inhibit-file-name-operation))
540         (inhibit-file-name-handlers
541          (if inhibit
542              (append mm-inhibit-file-name-handlers 
543                      inhibit-file-name-handlers)
544            inhibit-file-name-handlers)))
545     (write-region start end filename append visit lockname)))
546
547 (provide 'mm-util)
548
549 ;;; mm-util.el ends here