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