dfa1d06a696eb58beb59d40ae28349d0223af11b
[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-decode-string (string)
168   "Decode STRING which is encoded in quoted-printable, and return the result."
169   (let (q h l)
170     (mapconcat (function
171                 (lambda (chr)
172                   (cond ((eq chr ?=)
173                          (setq q t)
174                          "")
175                         (q (setq h (quoted-printable-hex-char-to-num chr))
176                            (setq q nil)
177                            "")
178                         (h (setq l (quoted-printable-hex-char-to-num chr))
179                            (prog1
180                                (char-to-string (logior (ash h 4) l))
181                              (setq h nil)
182                              )
183                            )
184                         (t (char-to-string chr))
185                         )))
186                string "")))
187
188 (defun quoted-printable-internal-decode-region (start end)
189   (save-excursion
190     (save-restriction
191       (narrow-to-region start end)
192       (goto-char (point-min))
193       (while (re-search-forward "=\n" nil t)
194         (replace-match "")
195         )
196       (goto-char (point-min))
197       (let (b e str)
198         (while (re-search-forward quoted-printable-octet-regexp nil t)
199           (setq b (match-beginning 0))
200           (setq e (match-end 0))
201           (setq str (buffer-substring b e))
202           (delete-region b e)
203           (insert (string-as-multibyte (quoted-printable-decode-string str)))
204           ))
205       )))
206
207
208 (defvar quoted-printable-external-decoder '("mmencode" "-q" "-u")
209   "*list of quoted-printable decoder program name and its arguments.")
210
211 (defun quoted-printable-external-decode-region (start end)
212   (save-excursion
213     (as-binary-process
214      (apply (function call-process-region)
215             start end (car quoted-printable-external-decoder)
216             t t nil (cdr quoted-printable-external-decoder))
217      )))
218
219
220 (defvar quoted-printable-internal-decoding-limit nil
221   "*limit size to use internal quoted-printable decoder.
222 If size of input to decode is larger than this limit,
223 external decoder is called.")
224
225 (defun quoted-printable-decode-region (start end)
226   "Decode current region by quoted-printable.
227 START and END are buffer positions.
228 This function calls internal quoted-printable decoder if size of
229 region is smaller than `quoted-printable-internal-decoding-limit',
230 otherwise it calls external quoted-printable decoder specified by
231 `quoted-printable-external-decoder'.  In this case, you must install
232 the program (maybe mmencode included in metamail or XEmacs package)."
233   (interactive "r")
234   (if (and quoted-printable-internal-decoding-limit
235            (> (- end start) quoted-printable-internal-decoding-limit))
236       (quoted-printable-external-decode-region start end)
237     (quoted-printable-internal-decode-region start end)
238     ))
239
240
241 (defvar quoted-printable-external-decoder-option-to-specify-file '("-o")
242   "*list of options of quoted-printable decoder program to specify file.")
243
244 (defun quoted-printable-write-decoded-region (start end filename)
245   "Decode and write current region encoded by quoted-printable into FILENAME.
246 START and END are buffer positions."
247   (interactive
248    (list (region-beginning) (region-end)
249          (read-file-name "Write decoded region to file: ")))
250   (as-binary-process
251    (apply (function call-process-region)
252           start end (car quoted-printable-external-decoder)
253           nil nil nil
254           (append (cdr quoted-printable-external-decoder)
255                   quoted-printable-external-decoder-option-to-specify-file
256                   (list filename))
257           )))
258
259 \f
260 ;;; @ Q-encoding encode/decode string
261 ;;;
262
263 (defconst q-encoding-special-chars-alist
264   '((text       ?= ?? ?_)
265     (comment    ?= ?? ?_ ?\( ?\) ?\\)
266     (phrase     ?= ?? ?_ ?\( ?\) ?\\ ?\" ?# ?$ ?% ?& ?' ?, ?. ?/
267                 ?: ?\; ?< ?> ?@ ?\[ ?\] ?^ ?` ?{ ?| ?} ?~)
268     ))
269
270 (defun q-encoding-encode-string (string &optional mode)
271   "Encode STRING to Q-encoding of encoded-word, and return the result.
272 MODE allows `text', `comment', `phrase' or nil.  Default value is
273 `phrase'."
274   (let ((specials (cdr (or (assq mode q-encoding-special-chars-alist)
275                            (assq 'phrase q-encoding-special-chars-alist)
276                            ))))
277     (mapconcat (function
278                 (lambda (chr)
279                   (cond ((eq chr ? ) "_")
280                         ((or (< chr 32) (< 126 chr)
281                              (memq chr specials)
282                              )
283                          (quoted-printable-quote-char chr)
284                          )
285                         (t
286                          (char-to-string chr)
287                          ))
288                   ))
289                string "")
290     ))
291
292 (defun q-encoding-decode-string (string)
293   "Decode STRING which is encoded in Q-encoding and return the result."
294   (let (q h l)
295     (mapconcat (function
296                 (lambda (chr)
297                   (cond ((eq chr ?_) " ")
298                         ((eq chr ?=)
299                          (setq q t)
300                          "")
301                         (q (setq h (quoted-printable-hex-char-to-num chr))
302                            (setq q nil)
303                            "")
304                         (h (setq l (quoted-printable-hex-char-to-num chr))
305                            (prog1
306                                (char-to-string (logior (ash h 4) l))
307                              (setq h nil)
308                              )
309                            )
310                         (t (char-to-string chr))
311                         )))
312                string "")))
313
314
315 ;;; @@ etc
316 ;;;
317
318 (defun q-encoding-printable-char-p (chr mode)
319   (and (not (memq chr '(?= ?? ?_)))
320        (<= ?\   chr)(<= chr ?~)
321        (cond ((eq mode 'text) t)
322              ((eq mode 'comment)
323               (not (memq chr '(?\( ?\) ?\\)))
324               )
325              (t
326               (string-match "[A-Za-z0-9!*+/=_---]" (char-to-string chr))
327               ))))
328
329 (defun q-encoding-encoded-length (string &optional mode)
330   (let ((l 0)(i 0)(len (length string)) chr)
331     (while (< i len)
332       (setq chr (elt string i))
333       (if (q-encoding-printable-char-p chr mode)
334           (setq l (+ l 1))
335         (setq l (+ l 3))
336         )
337       (setq i (+ i 1)) )
338     l))
339
340
341 ;;; @ end
342 ;;;
343
344 (provide 'mel-q)
345
346 ;;; mel-q.el ends here