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