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