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