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