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