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