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