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