ptexinfmt.el; Fix last change
[elisp/wanderlust.git] / elmo / 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 ;; 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
20 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;; UTF-7 - A Mail-Safe Transformation Format of Unicode - RFC 2152
26 ;; This is a transformation format of Unicode that contains only 7-bit
27 ;; ASCII octets and is intended to be readable by humans in the limiting
28 ;; case that the document consists of characters from the US-ASCII
29 ;; repertoire.
30 ;; In short, runs of characters outside US-ASCII are encoded as base64
31 ;; inside delimiters.
32 ;; A variation of UTF-7 is specified in IMAP 4rev1 (RFC 2060) as the way
33 ;; to represent characters outside US-ASCII in mailbox names in IMAP.
34 ;; This library supports both variants, but the IMAP variation was the
35 ;; reason I wrote it.
36 ;; The routines convert UTF-7 -> UTF-16 (16 bit encoding of Unicode)
37 ;; -> current character set, and vice versa.
38 ;; However, until Emacs supports Unicode, the only Emacs character set
39 ;; supported here is ISO-8859.1, which can trivially be converted to/from
40 ;; Unicode.
41 ;; When decoding results in a character outside the Emacs character set,
42 ;; an error is thrown.  It is up to the application to recover.
43
44 ;; UTF-7 should be done by providing a coding system.  Mule-UCS does
45 ;; already, but I don't know if it does the IMAP version and it's not
46 ;; clear whether that should really be a coding system.  The UTF-16
47 ;; part of the conversion can be done with coding systems available
48 ;; with Mule-UCS or some versions of Emacs.  Unfortunately these were
49 ;; done wrongly (regarding handling of byte-order marks and how the
50 ;; variants were named), so we don't have a consistent name for the
51 ;; necessary coding system.  The code below doesn't seem to DTRT
52 ;; generally.  E.g.:
53 ;;
54 ;; (utf7-encode "a+£")
55 ;;   => "a+ACsAow-"
56 ;;
57 ;; $ echo "a+£"|iconv -f iso-8859-1 -t utf-7
58 ;; a+-+AKM
59 ;;
60 ;;  -- fx
61
62 ;; Modified 5 May 2004 by Yuuichi Teranishi so that it can run with APEL/FLIM
63 ;; instead of mm-util in Gnus.
64 ;;
65 ;; * Use find-coding-system instead of mm-coding-system-p.
66 ;; * Use mel.el instead of base64.el.
67 ;; * Don't use mm-with-unibyte-current-buffer etc.
68 ;; * Do nothing if utf-16 coding system is not found.
69
70 ;; Modified 31 Aug 2004 by Yuuichi Teranishi so that it can avoid the bug of
71 ;; Emacs 21.3 release version.
72
73 ;;; Code:
74
75 (eval-when-compile (require 'cl))
76 (require 'pces)
77 (require 'mel)
78
79 ;; base64 encoding/decoding
80 (defun utf7-base64-encode-region (beg end &optional no-line-break))
81 (defun utf7-base64-decode-region (beg end))
82 (fset 'utf7-base64-encode-region
83       (mel-find-function 'mime-encode-region "base64"))
84 (fset 'utf7-base64-decode-region
85       (mel-find-function 'mime-decode-region "base64"))
86
87 (defconst utf7-direct-encoding-chars " -%'-*,-[]-}"
88   "Character ranges which do not need escaping in UTF-7.")
89
90 (defconst utf7-imap-direct-encoding-chars
91   (concat utf7-direct-encoding-chars "+\\~")
92   "Character ranges which do not need escaping in the IMAP variant of UTF-7.")
93
94
95 (eval-and-compile
96   (defun utf7-find-coding-system-without-bom (cs)
97     (and (fboundp 'find-coding-system)
98          (find-coding-system cs)
99          ;; Avoid versions with BOM.
100          (= 2 (length (encode-coding-string "a" cs)))
101          cs)))
102
103 (defconst utf7-utf-16-coding-system
104   (or
105    ;; Emacs 22, Emacs 23
106    (utf7-find-coding-system-without-bom 'utf-16be)
107    ;;
108    (utf7-find-coding-system-without-bom 'utf-16-be)
109    ;; Mule-UCS
110    (utf7-find-coding-system-without-bom 'utf-16-be-no-signature))
111   "Coding system which encodes big endian UTF-16.")
112
113 (defsubst utf7-imap-get-pad-length (len modulus)
114   "Return required length of padding for IMAP modified base64 fragment."
115   (mod (- len) modulus))
116
117 (defun utf7-encode-internal (&optional for-imap)
118   "Encode text in (temporary) buffer as UTF-7.
119 Use IMAP modification if FOR-IMAP is non-nil."
120   (let ((start (point-min))
121         (end (point-max)))
122     (narrow-to-region start end)
123     (goto-char start)
124     (let* ((esc-char (if for-imap ?& ?+))
125            (direct-encoding-chars
126             (if for-imap utf7-imap-direct-encoding-chars
127               utf7-direct-encoding-chars))
128            (not-direct-encoding-chars (concat "^" direct-encoding-chars)))
129       (while (not (eobp))
130         (skip-chars-forward direct-encoding-chars)
131         (unless (eobp)
132           (insert esc-char)
133           (let ((p (point))
134                 (fc (following-char))
135                 (run-length
136                  (skip-chars-forward not-direct-encoding-chars)))
137             (if (and (= fc esc-char)
138                      (= run-length 1))  ; Lone esc-char?
139                 (delete-char -1)        ; Now there's one too many
140               (utf7-fragment-encode p (point) for-imap))
141             (insert "-")))))))
142
143 (defun utf7-fragment-encode (start end &optional for-imap)
144   "Encode text from START to END in buffer as UTF-7 escape fragment.
145 Use IMAP modification if FOR-IMAP is non-nil."
146   (let ((converter (utf7-get-u16char-converter 'to-utf-16))
147         (str (buffer-substring start end))
148         pm)
149     (when converter
150       (delete-region start end)
151       (goto-char start)
152       (insert
153        (with-temp-buffer
154          (insert str)
155          (funcall converter)
156          (set-buffer-multibyte nil)
157          (utf7-base64-encode-region (point-min) (point-max))
158          (goto-char (point-min))
159          (setq pm (point-max))
160          (when for-imap
161            (while (search-forward "/" nil t)
162              (replace-match ",")))
163          (skip-chars-forward "^= \t\n" pm)
164          (delete-region (point) pm)
165          (buffer-string))))))
166
167 (defun utf7-decode-internal (&optional for-imap)
168   "Decode UTF-7 text in (temporary) buffer.
169 Use IMAP modification if FOR-IMAP is non-nil."
170   (let ((start (point-min))
171         (end (point-max)))
172     (goto-char start)
173     (let* ((esc-pattern (concat "^" (char-to-string (if for-imap ?& ?+))))
174            (base64-chars (concat "A-Za-z0-9+"
175                                  (char-to-string (if for-imap ?, ?/)))))
176       (while (not (eobp))
177         (skip-chars-forward esc-pattern)
178         (unless (eobp)
179           (forward-char)
180           (let ((p (point))
181                 (run-length (skip-chars-forward base64-chars)))
182             (when (and (not (eobp)) (= (following-char) ?-))
183               (delete-char 1))
184             (unless (= run-length 0)    ; Encoded lone esc-char?
185               (save-excursion
186                 (utf7-fragment-decode p (point) for-imap)
187                 (goto-char p)
188                 (delete-char -1)))))))))
189
190 (defun utf7-fragment-decode (start end &optional for-imap)
191   "Decode base64 encoded fragment from START to END of UTF-7 text in buffer.
192 Use IMAP modification if FOR-IMAP is non-nil."
193   (save-restriction
194     (narrow-to-region start end)
195     (let ((converter (utf7-get-u16char-converter 'from-utf-16)))
196       (when converter
197         (when for-imap
198           (goto-char start)
199           (while (search-forward "," nil 'move-to-end) (replace-match "/")))
200         (let ((pl (utf7-imap-get-pad-length (- end start) 4)))
201           (insert (make-string pl ?=))
202           (utf7-base64-decode-region start (+ end pl)))
203         (funcall converter)))))
204
205 (defun utf7-get-u16char-converter (which-way)
206   "Return a function to convert between UTF-16 and current character set."
207   (if utf7-utf-16-coding-system
208       (if (eq which-way 'to-utf-16)
209           (lambda ()
210             (encode-coding-region (point-min)(point-max)
211                                   utf7-utf-16-coding-system)
212             (set-buffer-multibyte nil)
213             (goto-char (point-min))
214             ;; Remove BOM (Big-endian UTF-16 FE FF) for Mule-UCS
215             (while (re-search-forward "\376\377" nil t)
216               (delete-region (match-beginning 0) (match-end 0))))
217         (lambda ()
218           (goto-char (point-min))
219           (decode-coding-region (point-min) (point-max)
220                                 utf7-utf-16-coding-system)))))
221
222 (defun utf7-encode (string &optional for-imap)
223   "Encode UTF-7 STRING.  Use IMAP modification if FOR-IMAP is non-nil."
224   (let ((default-enable-multibyte-characters t))
225     (with-temp-buffer
226       (insert string)
227       (utf7-encode-internal for-imap)
228       (buffer-string))))
229
230 (defun utf7-decode (string &optional for-imap)
231   "Decode UTF-7 STRING.  Use IMAP modification if FOR-IMAP is non-nil."
232   (let ((default-enable-multibyte-characters nil))
233     (with-temp-buffer
234       (insert string)
235       (utf7-decode-internal for-imap)
236       (set-buffer-multibyte t)
237       (buffer-string))))
238
239 (defalias 'utf7-encode-string 'utf7-encode)
240 (defalias 'utf7-decode-string 'utf7-decode)
241
242 (provide 'utf7)
243
244 ;;; utf7.el ends here