(quoted-printable-decode-string): New implementation.
[elisp/flim.git] / mel-q.el
1 ;;; mel-q.el: Quoted-Printable and Q-encoding encoder/decoder for GNU Emacs
2
3 ;; Copyright (C) 1995,1996,1997,1998 Free Software Foundation, Inc.
4
5 ;; Author: MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; Created: 1995/6/25
7 ;; Keywords: MIME, Quoted-Printable, Q-encoding
8
9 ;; This file is part of MEL (MIME Encoding Library).
10
11 ;; This program is free software; you can redistribute it and/or
12 ;; modify it under the terms of the GNU General Public License as
13 ;; published by the Free Software Foundation; either version 2, or (at
14 ;; your option) any later version.
15
16 ;; This program is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Code:
27
28 (require 'emu)
29 (require 'mime-def)
30
31
32 ;;; @ Quoted-Printable encoder
33 ;;;
34
35 (defsubst quoted-printable-quote-char (character)
36   (concat
37    "="
38    (char-to-string (aref quoted-printable-hex-chars (ash character -4)))
39    (char-to-string (aref quoted-printable-hex-chars (logand character 15)))
40    ))
41
42 (defun quoted-printable-internal-encode-region (start end)
43   (save-excursion
44     (save-restriction
45       (narrow-to-region start end)
46       (goto-char start)
47       (let ((col 0))
48         (while (< (point)(point-max))
49           (cond ((>= col 75)
50                  (insert "=\n")
51                  (setq col 0)
52                  )
53                 ((looking-at-as-unibyte "^From ")
54                  (replace-match "=46rom ")
55                  (backward-char 1)
56                  (setq col (+ col 6))
57                  )
58                 ((looking-at-as-unibyte "[ \t]\n")
59                  (forward-char 1)
60                  (insert "=\n")
61                  (forward-char 1)
62                  (setq col 0)
63                  )
64                 (t
65                  (let ((chr (char-after (point))))
66                    (cond ((= chr ?\n)
67                           (forward-char 1)
68                           (setq col 0)
69                           )
70                          ((or (= chr ?\t)
71                               (and (<= 32 chr)(/= chr ?=)(< chr 127))
72                               )
73                           (forward-char 1)
74                           (setq col (1+ col))
75                           )
76                          ((>= col 73)
77                           (insert "=\n")
78                           (setq col 0)
79                           )
80                          (t
81                           (delete-char 1)
82                           (insert (quoted-printable-quote-char chr))
83                           (setq col (+ col 3))
84                           ))
85                    )))
86           )))))
87
88
89 (defvar quoted-printable-external-encoder '("mmencode" "-q")
90   "*list of quoted-printable encoder program name and its arguments.")
91
92 (defun quoted-printable-external-encode-region (start end)
93   (save-excursion
94     (save-restriction
95       (narrow-to-region start end)
96       (as-binary-process
97        (apply (function call-process-region)
98               start end (car quoted-printable-external-encoder)
99               t t nil (cdr quoted-printable-external-encoder))
100        )
101       ;; for OS/2
102       ;;   regularize line break code
103       (goto-char (point-min))
104       (while (re-search-forward "\r$" nil t)
105         (replace-match "")
106         )
107       )))
108
109
110 (defvar quoted-printable-internal-encoding-limit
111   (if (and (featurep 'xemacs)(featurep 'mule))
112       0
113     (require 'path-util)
114     (if (exec-installed-p "mmencode")
115         1000
116       (message "Don't found external encoder for Quoted-Printable!")
117       nil))
118   "*limit size to use internal quoted-printable encoder.
119 If size of input to encode is larger than this limit,
120 external encoder is called.")
121
122 (defun quoted-printable-encode-region (start end)
123   "Encode current region by quoted-printable.
124 START and END are buffer positions.
125 This function calls internal quoted-printable encoder if size of
126 region is smaller than `quoted-printable-internal-encoding-limit',
127 otherwise it calls external quoted-printable encoder specified by
128 `quoted-printable-external-encoder'.  In this case, you must install
129 the program (maybe mmencode included in metamail or XEmacs package)."
130   (interactive "r")
131   (if (and quoted-printable-internal-encoding-limit
132            (> (- end start) quoted-printable-internal-encoding-limit))
133       (quoted-printable-external-encode-region start end)
134     (quoted-printable-internal-encode-region start end)
135     ))
136
137
138 (defun quoted-printable-encode-string (string)
139   "Encode STRING to quoted-printable, and return the result."
140   (with-temp-buffer
141     (insert string)
142     (quoted-printable-encode-region (point-min)(point-max))
143     (buffer-string)
144     ))
145
146
147 (defun quoted-printable-insert-encoded-file (filename)
148   "Encode contents of file FILENAME to quoted-printable, and insert the result.
149 It calls external quoted-printable encoder specified by
150 `quoted-printable-external-encoder'.  So you must install the program
151 \(maybe mmencode included in metamail or XEmacs package)."
152   (interactive (list (read-file-name "Insert encoded file: ")))
153   (apply (function call-process) (car quoted-printable-external-encoder)
154          filename t nil (cdr quoted-printable-external-encoder))
155   )
156
157
158 ;;; @ Quoted-Printable decoder
159 ;;;
160
161 (defsubst quoted-printable-hex-char-to-num (chr)
162   (cond ((<= ?a chr) (+ (- chr ?a) 10))
163         ((<= ?A chr) (+ (- chr ?A) 10))
164         ((<= ?0 chr) (- chr ?0))
165         ))
166
167 (defun quoted-printable-internal-decode-region (start end)
168   (save-excursion
169     (save-restriction
170       (narrow-to-region start end)
171       (goto-char (point-min))
172       (while (search-forward "=" nil t)
173         (let ((beg (match-beginning 0)))
174           (cond ((looking-at "\n")
175                  (delete-region beg (match-end 0))
176                  )
177                 ((looking-at
178                   `,(concat "[" quoted-printable-hex-chars
179                             "][" quoted-printable-hex-chars "]"))
180                  (let* ((end (match-end 0))
181                         (hex (buffer-substring (match-beginning 0) end)))
182                    (delete-region beg end)
183                    (insert
184                     (logior
185                      (ash (quoted-printable-hex-char-to-num (aref hex 0)) 4)
186                      (quoted-printable-hex-char-to-num (aref hex 1))))
187                    ))
188                 (t
189                  ;; invalid
190                  ))
191           )))))
192
193 (defvar quoted-printable-external-decoder '("mmencode" "-q" "-u")
194   "*list of quoted-printable decoder program name and its arguments.")
195
196 (defun quoted-printable-external-decode-region (start end)
197   (save-excursion
198     (as-binary-process
199      (apply (function call-process-region)
200             start end (car quoted-printable-external-decoder)
201             t t nil (cdr quoted-printable-external-decoder))
202      )))
203
204
205 (defvar quoted-printable-internal-decoding-limit nil
206   "*limit size to use internal quoted-printable decoder.
207 If size of input to decode is larger than this limit,
208 external decoder is called.")
209
210 (defun quoted-printable-decode-region (start end)
211   "Decode current region by quoted-printable.
212 START and END are buffer positions.
213 This function calls internal quoted-printable decoder if size of
214 region is smaller than `quoted-printable-internal-decoding-limit',
215 otherwise it calls external quoted-printable decoder specified by
216 `quoted-printable-external-decoder'.  In this case, you must install
217 the program (maybe mmencode included in metamail or XEmacs package)."
218   (interactive "r")
219   (if (and quoted-printable-internal-decoding-limit
220            (> (- end start) quoted-printable-internal-decoding-limit))
221       (quoted-printable-external-decode-region start end)
222     (quoted-printable-internal-decode-region start end)
223     ))
224
225 (defun quoted-printable-decode-string (string)
226   "Decode STRING which is encoded in quoted-printable, and return the result."
227   (with-temp-buffer
228     (insert string)
229     (quoted-printable-decode-region (point-min)(point-max))
230     (buffer-string)))
231
232
233 (defvar quoted-printable-external-decoder-option-to-specify-file '("-o")
234   "*list of options of quoted-printable decoder program to specify file.")
235
236 (defun quoted-printable-write-decoded-region (start end filename)
237   "Decode and write current region encoded by quoted-printable into FILENAME.
238 START and END are buffer positions."
239   (interactive
240    (list (region-beginning) (region-end)
241          (read-file-name "Write decoded region to file: ")))
242   (as-binary-process
243    (apply (function call-process-region)
244           start end (car quoted-printable-external-decoder)
245           nil nil nil
246           (append (cdr quoted-printable-external-decoder)
247                   quoted-printable-external-decoder-option-to-specify-file
248                   (list filename))
249           )))
250
251 \f
252 ;;; @ Q-encoding encode/decode string
253 ;;;
254
255 (defconst q-encoding-special-chars-alist
256   '((text       ?= ?? ?_)
257     (comment    ?= ?? ?_ ?\( ?\) ?\\)
258     (phrase     ?= ?? ?_ ?\( ?\) ?\\ ?\" ?# ?$ ?% ?& ?' ?, ?. ?/
259                 ?: ?\; ?< ?> ?@ ?\[ ?\] ?^ ?` ?{ ?| ?} ?~)
260     ))
261
262 (defun q-encoding-encode-string (string &optional mode)
263   "Encode STRING to Q-encoding of encoded-word, and return the result.
264 MODE allows `text', `comment', `phrase' or nil.  Default value is
265 `phrase'."
266   (let ((specials (cdr (or (assq mode q-encoding-special-chars-alist)
267                            (assq 'phrase q-encoding-special-chars-alist)
268                            ))))
269     (mapconcat (function
270                 (lambda (chr)
271                   (cond ((eq chr ? ) "_")
272                         ((or (< chr 32) (< 126 chr)
273                              (memq chr specials)
274                              )
275                          (quoted-printable-quote-char chr)
276                          )
277                         (t
278                          (char-to-string chr)
279                          ))
280                   ))
281                string "")
282     ))
283
284 (defun q-encoding-decode-string (string)
285   "Decode STRING which is encoded in Q-encoding and return the result."
286   (let (q h l)
287     (mapconcat (function
288                 (lambda (chr)
289                   (cond ((eq chr ?_) " ")
290                         ((eq chr ?=)
291                          (setq q t)
292                          "")
293                         (q (setq h (quoted-printable-hex-char-to-num chr))
294                            (setq q nil)
295                            "")
296                         (h (setq l (quoted-printable-hex-char-to-num chr))
297                            (prog1
298                                (char-to-string (logior (ash h 4) l))
299                              (setq h nil)
300                              )
301                            )
302                         (t (char-to-string chr))
303                         )))
304                string "")))
305
306
307 ;;; @@ etc
308 ;;;
309
310 (defun q-encoding-printable-char-p (chr mode)
311   (and (not (memq chr '(?= ?? ?_)))
312        (<= ?\   chr)(<= chr ?~)
313        (cond ((eq mode 'text) t)
314              ((eq mode 'comment)
315               (not (memq chr '(?\( ?\) ?\\)))
316               )
317              (t
318               (string-match "[A-Za-z0-9!*+/=_---]" (char-to-string chr))
319               ))))
320
321 (defun q-encoding-encoded-length (string &optional mode)
322   (let ((l 0)(i 0)(len (length string)) chr)
323     (while (< i len)
324       (setq chr (elt string i))
325       (if (q-encoding-printable-char-p chr mode)
326           (setq l (+ l 1))
327         (setq l (+ l 3))
328         )
329       (setq i (+ i 1)) )
330     l))
331
332
333 ;;; @ end
334 ;;;
335
336 (provide 'mel-q)
337
338 ;;; mel-q.el ends here