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