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