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