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