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