Synch to No Gnus 200405210034.
[elisp/gnus.git-] / lisp / utf7.el
1 ;;; utf7.el --- UTF-7 encoding/decoding for Emacs   -*-coding: iso-8859-1;-*-
2 ;; Copyright (C) 1999, 2000, 2003 Free Software Foundation, Inc.
3
4 ;; Author: Jon K Hellan <hellan@acm.org>
5 ;; Maintainer: bugs@gnus.org
6 ;; Keywords: mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to
22 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; UTF-7 - A Mail-Safe Transformation Format of Unicode - RFC 2152
28 ;; This is a transformation format of Unicode that contains only 7-bit
29 ;; ASCII octets and is intended to be readable by humans in the limiting
30 ;; case that the document consists of characters from the US-ASCII
31 ;; repertoire.
32 ;; In short, runs of characters outside US-ASCII are encoded as base64
33 ;; inside delimiters.
34 ;; A variation of UTF-7 is specified in IMAP 4rev1 (RFC 2060) as the way
35 ;; to represent characters outside US-ASCII in mailbox names in IMAP.
36 ;; This library supports both variants, but the IMAP variation was the
37 ;; reason I wrote it.
38 ;; The routines convert UTF-7 -> UTF-16 (16 bit encoding of Unicode)
39 ;; -> current character set, and vice versa.
40 ;; However, until Emacs supports Unicode, the only Emacs character set
41 ;; supported here is ISO-8859.1, which can trivially be converted to/from
42 ;; Unicode.
43 ;; When decoding results in a character outside the Emacs character set,
44 ;; an error is thrown.  It is up to the application to recover.
45
46 ;; UTF-7 should be done by providing a coding system.  Mule-UCS does
47 ;; already, but I don't know if it does the IMAP version and it's not
48 ;; clear whether that should really be a coding system.  The UTF-16
49 ;; part of the conversion can be done with coding systems available
50 ;; with Mule-UCS or some versions of Emacs.  Unfortunately these were
51 ;; done wrongly (regarding handling of byte-order marks and how the
52 ;; variants were named), so we don't have a consistent name for the
53 ;; necessary coding system.  The code below doesn't seem to DTRT
54 ;; generally.  E.g.:
55 ;;
56 ;; (utf7-encode "a+£")
57 ;;   => "a+ACsAow-"
58 ;;
59 ;; $ echo "a+£"|iconv -f iso-8859-1 -t utf-7
60 ;; a+-+AKM
61 ;;
62 ;;  -- fx 
63
64
65 ;;; Code:
66
67 (require 'base64)
68 (eval-when-compile
69   (require 'cl)
70   (require 'mm-util))
71
72 (defconst utf7-direct-encoding-chars " -%'-*,-[]-}"
73   "Character ranges which do not need escaping in UTF-7.")
74
75 (defconst utf7-imap-direct-encoding-chars
76   (concat utf7-direct-encoding-chars "+\\~")
77   "Character ranges which do not need escaping in the IMAP variant of UTF-7.")
78
79 (defconst utf7-utf-16-coding-system
80   (cond ((mm-coding-system-p 'utf-16-be-no-signature) ; Mule-UCS
81          'utf-16-be-no-signature)
82         ((and (mm-coding-system-p 'utf-16-be) ; Emacs 21.4 (?), Emacs 22
83               ;; Avoid versions with BOM.
84               (= 2 (length (encode-coding-string "a" 'utf-16-be))))
85          'utf-16-be)
86         ((mm-coding-system-p 'utf-16-be-nosig) ; ?
87          'utf-16-be-nosig))
88   "Coding system which encodes big endian UTF-16 without a BOM signature.")
89
90 (defsubst utf7-imap-get-pad-length (len modulus)
91   "Return required length of padding for IMAP modified base64 fragment."
92   (mod (- len) modulus))
93
94 (defun utf7-encode-internal (&optional for-imap)
95   "Encode text in (temporary) buffer as UTF-7.
96 Use IMAP modification if FOR-IMAP is non-nil."
97   (let ((start (point-min))
98         (end (point-max)))
99     (narrow-to-region start end)
100     (goto-char start)
101     (let* ((esc-char (if for-imap ?& ?+))
102            (direct-encoding-chars
103             (if for-imap utf7-imap-direct-encoding-chars
104               utf7-direct-encoding-chars))
105            (not-direct-encoding-chars (concat "^" direct-encoding-chars)))
106       (while (not (eobp))
107         (skip-chars-forward direct-encoding-chars)
108         (unless (eobp)
109           (insert esc-char)
110           (let ((p (point))
111                 (fc (following-char))
112                 (run-length
113                  (skip-chars-forward not-direct-encoding-chars)))
114             (if (and (= fc esc-char)
115                      (= run-length 1))  ; Lone esc-char?
116                 (delete-backward-char 1) ; Now there's one too many
117               (utf7-fragment-encode p (point) for-imap))
118             (insert "-")))))))
119
120 (defun utf7-fragment-encode (start end &optional for-imap)
121   "Encode text from START to END in buffer as UTF-7 escape fragment.
122 Use IMAP modification if FOR-IMAP is non-nil."
123   (save-restriction
124     (narrow-to-region start end)
125     (funcall (utf7-get-u16char-converter 'to-utf-16))
126     (mm-with-unibyte-current-buffer
127       (base64-encode-region start (point-max)))
128     (goto-char start)
129     (let ((pm (point-max)))
130       (when for-imap
131         (while (search-forward "/" nil t)
132           (replace-match ",")))
133       (skip-chars-forward "^= \t\n" pm)
134       (delete-region (point) pm))))
135
136 (defun utf7-decode-internal (&optional for-imap)
137   "Decode UTF-7 text in (temporary) buffer.
138 Use IMAP modification if FOR-IMAP is non-nil."
139   (let ((start (point-min))
140         (end (point-max)))
141     (goto-char start)
142     (let* ((esc-pattern (concat "^" (char-to-string (if for-imap ?& ?+))))
143            (base64-chars (concat "A-Za-z0-9+"
144                                  (char-to-string (if for-imap ?, ?/)))))
145       (while (not (eobp))
146         (skip-chars-forward esc-pattern)
147         (unless (eobp)
148           (forward-char)
149           (let ((p (point))
150                 (run-length (skip-chars-forward base64-chars)))
151             (when (and (not (eobp)) (= (following-char) ?-))
152               (delete-char 1))
153             (unless (= run-length 0)    ; Encoded lone esc-char?
154               (save-excursion
155                 (utf7-fragment-decode p (point) for-imap)
156                 (goto-char p)
157                 (delete-backward-char 1)))))))))
158
159 (defun utf7-fragment-decode (start end &optional for-imap)
160   "Decode base64 encoded fragment from START to END of UTF-7 text in buffer.
161 Use IMAP modification if FOR-IMAP is non-nil."
162   (save-restriction
163     (narrow-to-region start end)
164     (when for-imap
165       (goto-char start)
166       (while (search-forward "," nil 'move-to-end) (replace-match "/")))
167     (let ((pl (utf7-imap-get-pad-length (- end start) 4)))
168       (insert (make-string pl ?=))
169       (base64-decode-region start (+ end pl)))
170     (funcall (utf7-get-u16char-converter 'from-utf-16))))
171
172 (defun utf7-get-u16char-converter (which-way)
173   "Return a function to convert between UTF-16 and current character set."
174   (if utf7-utf-16-coding-system
175       (if (eq which-way 'to-utf-16)
176           (lambda ()
177             (encode-coding-region (point-min) (point-max)
178                                   utf7-utf-16-coding-system))
179         (lambda ()
180           (decode-coding-region (point-min) (point-max)
181                                 utf7-utf-16-coding-system)))
182     ;; Add test to check if we are really Latin-1.
183     (if (eq which-way 'to-utf-16)
184         'utf7-latin1-u16-char-converter
185       'utf7-u16-latin1-char-converter)))
186
187 (defun utf7-latin1-u16-char-converter ()
188   "Convert latin 1 (ISO-8859.1) characters to 16 bit Unicode.
189 Characters are converted to raw byte pairs in narrowed buffer."
190   (mm-encode-coding-region (point-min) (point-max) 'iso-8859-1)
191   (mm-disable-multibyte)
192   (goto-char (point-min))
193   (while (not (eobp))
194     (insert 0)
195     (forward-char)))
196
197 (defun utf7-u16-latin1-char-converter ()
198   "Convert 16 bit Unicode characters to latin 1 (ISO-8859.1).
199 Characters are in raw byte pairs in narrowed buffer."
200   (goto-char (point-min))
201   (while (not (eobp))
202     (if (= 0 (following-char))
203         (delete-char 1)
204       (error "Unable to convert from Unicode"))
205     (forward-char))
206   (mm-decode-coding-region (point-min) (point-max) 'iso-8859-1)
207   (mm-enable-multibyte))
208
209 (defun utf7-encode (string &optional for-imap)
210   "Encode UTF-7 STRING.  Use IMAP modification if FOR-IMAP is non-nil."
211   (let ((default-enable-multibyte-characters t))
212     (with-temp-buffer
213       (insert string)
214       (utf7-encode-internal for-imap)
215       (buffer-string))))
216
217 (defun utf7-decode (string &optional for-imap)
218   "Decode UTF-7 STRING.  Use IMAP modification if FOR-IMAP is non-nil."
219   (let ((default-enable-multibyte-characters nil))
220     (with-temp-buffer
221       (insert string)
222       (utf7-decode-internal for-imap)
223       (mm-enable-multibyte)
224       (buffer-string))))
225
226 (provide 'utf7)
227
228 ;;; utf7.el ends here