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