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