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