(quoted-printable-external-decoder-option-to-specify-file): New
[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
30
31 ;;; @ Quoted-Printable encoder
32 ;;;
33
34 (defconst quoted-printable-hex-chars "0123456789ABCDEF")
35
36 (defsubst quoted-printable-quote-char (character)
37   (concat
38    "="
39    (char-to-string (aref quoted-printable-hex-chars (ash character -4)))
40    (char-to-string (aref quoted-printable-hex-chars (logand character 15)))
41    ))
42
43 (defun quoted-printable-internal-encode-region (start end)
44   (save-excursion
45     (save-restriction
46       (narrow-to-region start end)
47       (goto-char start)
48       (let ((col 0)
49             enable-multibyte-characters)
50         (while (< (point)(point-max))
51           (cond ((>= col 75)
52                  (insert "=\n")
53                  (setq col 0)
54                  )
55                 ((looking-at "^From ")
56                  (replace-match "=46rom ")
57                  (backward-char 1)
58                  (setq col (+ col 6))
59                  )
60                 ((looking-at "[ \t]\n")
61                  (forward-char 1)
62                  (insert "=\n")
63                  (forward-char 1)
64                  (setq col 0)
65                  )
66                 (t
67                  (let ((chr (char-after (point))))
68                    (cond ((= chr ?\n)
69                           (forward-char 1)
70                           (setq col 0)
71                           )
72                          ((or (= chr ?\t)
73                               (and (<= 32 chr)(/= chr ?=)(< chr 127))
74                               )
75                           (forward-char 1)
76                           (setq col (1+ col))
77                           )
78                          ((>= col 73)
79                           (insert "=\n")
80                           (setq col 0)
81                           )
82                          (t
83                           (delete-char 1)
84                           (insert (quoted-printable-quote-char chr))
85                           (setq col (+ col 3))
86                           ))
87                    )))
88           )))))
89
90
91 (defvar quoted-printable-external-encoder '("mmencode" "-q")
92   "*list of quoted-printable encoder program name and its arguments.")
93
94 (defun quoted-printable-external-encode-region (start end)
95   (save-excursion
96     (save-restriction
97       (narrow-to-region start end)
98       (as-binary-process
99        (apply (function call-process-region)
100               start end (car quoted-printable-external-encoder)
101               t t nil (cdr quoted-printable-external-encoder))
102        )
103       ;; for OS/2
104       ;;   regularize line break code
105       (goto-char (point-min))
106       (while (re-search-forward "\r$" nil t)
107         (replace-match "")
108         )
109       )))
110
111
112 (defvar quoted-printable-internal-encoding-limit
113   (if (and (featurep 'xemacs)(featurep 'mule))
114       0
115     (require 'path-util)
116     (if (exec-installed-p "mmencode")
117         1000
118       (message "Don't found external encoder for Quoted-Printable!")
119       nil))
120   "*limit size to use internal quoted-printable encoder.
121 If size of input to encode is larger than this limit,
122 external encoder is called.")
123
124 (defun quoted-printable-encode-region (start end)
125   "Encode current region by quoted-printable.
126 START and END are buffer positions.
127 This function calls internal quoted-printable encoder if size of
128 region is smaller than `quoted-printable-internal-encoding-limit',
129 otherwise it calls external quoted-printable encoder specified by
130 `quoted-printable-external-encoder'.  In this case, you must install
131 the program (maybe mmencode included in metamail or XEmacs package)."
132   (interactive "r")
133   (if (and quoted-printable-internal-encoding-limit
134            (> (- end start) quoted-printable-internal-encoding-limit))
135       (quoted-printable-external-encode-region start end)
136     (quoted-printable-internal-encode-region start end)
137     ))
138
139
140 (defun quoted-printable-encode-string (string)
141   "Encode STRING to quoted-printable, and return the result."
142   (with-temp-buffer
143     (insert string)
144     (quoted-printable-encode-region (point-min)(point-max))
145     (buffer-string)
146     ))
147
148
149 (defun quoted-printable-insert-encoded-file (filename)
150   "Encode contents of file FILENAME to quoted-printable, and insert the result.
151 It calls external quoted-printable encoder specified by
152 `quoted-printable-external-encoder'.  So you must install the program
153 \(maybe mmencode included in metamail or XEmacs package)."
154   (interactive (list (read-file-name "Insert encoded file: ")))
155   (apply (function call-process) (car quoted-printable-external-encoder)
156          filename t nil (cdr quoted-printable-external-encoder))
157   )
158
159
160 ;;; @ Quoted-Printable decoder
161 ;;;
162
163 (defun quoted-printable-decode-string (string)
164   "Decode STRING which is encoded in quoted-printable, and return the result."
165   (let (q h l)
166     (mapconcat (function
167                 (lambda (chr)
168                   (cond ((eq chr ?=)
169                          (setq q t)
170                          "")
171                         (q (setq h
172                                  (cond ((<= ?a chr) (+ (- chr ?a) 10))
173                                        ((<= ?A chr) (+ (- chr ?A) 10))
174                                        ((<= ?0 chr) (- chr ?0))
175                                        ))
176                            (setq q nil)
177                            "")
178                         (h (setq l (cond ((<= ?a chr) (+ (- chr ?a) 10))
179                                          ((<= ?A chr) (+ (- chr ?A) 10))
180                                          ((<= ?0 chr) (- chr ?0))
181                                          ))
182                            (prog1
183                                (char-to-string (logior (ash h 4) l))
184                              (setq h nil)
185                              )
186                            )
187                         (t (char-to-string chr))
188                         )))
189                string "")))
190
191 (defconst quoted-printable-octet-regexp
192   (concat "=[" quoted-printable-hex-chars
193           "][" quoted-printable-hex-chars "]"))
194
195 (defun quoted-printable-internal-decode-region (start end)
196   (save-excursion
197     (save-restriction
198       (narrow-to-region start end)
199       (goto-char (point-min))
200       (while (re-search-forward "=\n" nil t)
201         (replace-match "")
202         )
203       (goto-char (point-min))
204       (let (b e str)
205         (while (re-search-forward quoted-printable-octet-regexp nil t)
206           (setq b (match-beginning 0))
207           (setq e (match-end 0))
208           (setq str (buffer-substring b e))
209           (delete-region b e)
210           (insert (quoted-printable-decode-string str))
211           ))
212       )))
213
214
215 (defvar quoted-printable-external-decoder '("mmencode" "-q" "-u")
216   "*list of quoted-printable decoder program name and its arguments.")
217
218 (defun quoted-printable-external-decode-region (start end)
219   (save-excursion
220     (as-binary-process
221      (apply (function call-process-region)
222             start end (car quoted-printable-external-decoder)
223             t t nil (cdr quoted-printable-external-decoder))
224      )))
225
226
227 (defvar quoted-printable-internal-decoding-limit nil
228   "*limit size to use internal quoted-printable decoder.
229 If size of input to decode is larger than this limit,
230 external decoder is called.")
231
232 (defun quoted-printable-decode-region (start end)
233   "Decode current region by quoted-printable.
234 START and END are buffer positions.
235 This function calls internal quoted-printable decoder if size of
236 region is smaller than `quoted-printable-internal-decoding-limit',
237 otherwise it calls external quoted-printable decoder specified by
238 `quoted-printable-external-decoder'.  In this case, you must install
239 the program (maybe mmencode included in metamail or XEmacs package)."
240   (interactive "r")
241   (if (and quoted-printable-internal-decoding-limit
242            (> (- end start) quoted-printable-internal-decoding-limit))
243       (quoted-printable-external-decode-region start end)
244     (quoted-printable-internal-decode-region start end)
245     ))
246
247
248 (defvar quoted-printable-external-decoder-option-to-specify-file '("-o")
249   "*list of options of quoted-printable decoder program to specify file.")
250
251 (defun quoted-printable-write-decoded-region (start end filename)
252   "Decode and write current region encoded by quoted-printable into FILENAME.
253 START and END are buffer positions."
254   (interactive
255    (list (region-beginning) (region-end)
256          (read-file-name "Write decoded region to file: ")))
257   (as-binary-process
258    (apply (function call-process-region)
259           start end (car quoted-printable-external-decoder)
260           nil nil nil
261           (append (cdr quoted-printable-external-decoder)
262                   quoted-printable-external-decoder-option-to-specify-file
263                   (list filename))
264           )))
265
266 \f
267 ;;; @ Q-encoding encode/decode string
268 ;;;
269
270 (defconst q-encoding-special-chars-alist
271   '((text       ?= ?? ?_)
272     (comment    ?= ?? ?_ ?\( ?\) ?\\)
273     (phrase     ?= ?? ?_ ?\( ?\) ?\\ ?\" ?# ?$ ?% ?& ?' ?, ?. ?/
274                 ?: ?\; ?< ?> ?@ ?\[ ?\] ?^ ?` ?{ ?| ?} ?~)
275     ))
276
277 (defun q-encoding-encode-string (string &optional mode)
278   "Encode STRING to Q-encoding of encoded-word, and return the result.
279 MODE allows `text', `comment', `phrase' or nil.  Default value is
280 `phrase'."
281   (let ((specials (cdr (or (assq mode q-encoding-special-chars-alist)
282                            (assq 'phrase q-encoding-special-chars-alist)
283                            ))))
284     (mapconcat (function
285                 (lambda (chr)
286                   (cond ((eq chr ? ) "_")
287                         ((or (< chr 32) (< 126 chr)
288                              (memq chr specials)
289                              )
290                          (quoted-printable-quote-char chr)
291                          )
292                         (t
293                          (char-to-string chr)
294                          ))
295                   ))
296                string "")
297     ))
298
299 (defun q-encoding-decode-string (string)
300   "Decode STRING which is encoded in Q-encoding and return the result."
301   (let (q h l)
302     (mapconcat (function
303                 (lambda (chr)
304                   (cond ((eq chr ?_) " ")
305                         ((eq chr ?=)
306                          (setq q t)
307                          "")
308                         (q (setq h (cond ((<= ?a chr) (+ (- chr ?a) 10))
309                                          ((<= ?A chr) (+ (- chr ?A) 10))
310                                          ((<= ?0 chr) (- chr ?0))
311                                          ))
312                            (setq q nil)
313                            "")
314                         (h (setq l (cond ((<= ?a chr) (+ (- chr ?a) 10))
315                                          ((<= ?A chr) (+ (- chr ?A) 10))
316                                          ((<= ?0 chr) (- chr ?0))
317                                          ))
318                            (prog1
319                                (char-to-string (logior (ash h 4) l))
320                              (setq h nil)
321                              )
322                            )
323                         (t (char-to-string chr))
324                         )))
325                string "")))
326
327
328 ;;; @@ etc
329 ;;;
330
331 (defun q-encoding-printable-char-p (chr mode)
332   (and (not (memq chr '(?= ?? ?_)))
333        (<= ?\   chr)(<= chr ?~)
334        (cond ((eq mode 'text) t)
335              ((eq mode 'comment)
336               (not (memq chr '(?\( ?\) ?\\)))
337               )
338              (t
339               (string-match "[A-Za-z0-9!*+/=_---]" (char-to-string chr))
340               ))))
341
342 (defun q-encoding-encoded-length (string &optional mode)
343   (let ((l 0)(i 0)(len (length string)) chr)
344     (while (< i len)
345       (setq chr (elt string i))
346       (if (q-encoding-printable-char-p chr mode)
347           (setq l (+ l 1))
348         (setq l (+ l 3))
349         )
350       (setq i (+ i 1)) )
351     l))
352
353
354 ;;; @ end
355 ;;;
356
357 (provide 'mel-q)
358
359 ;;; mel-q.el ends here