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