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