(eword-generate-X-Nsubject): Don't refer variable
[elisp/semi.git] / eword-encode.el
1 ;;; eword-encode.el --- RFC 2047 based encoded-word encoder for GNU Emacs
2
3 ;; Copyright (C) 1995,1996,1997 Free Software Foundation, Inc.
4
5 ;; Author: MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; Version: $Revision: 0.4 $
7 ;; Keywords: encoded-word, MIME, multilingual, header, mail, news
8
9 ;; This file is part of SEMI (SEMI is Emacs MIME Interfaces).
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 'mel)
29 (require 'std11)
30 (require 'mime-def)
31 (require 'tl-list)
32
33
34 ;;; @ version
35 ;;;
36
37 (defconst eword-encode-RCS-ID
38   "$Id: eword-encode.el,v 0.4 1997-02-22 17:04:26 morioka Exp $")
39 (defconst eword-encode-version (get-version-string eword-encode-RCS-ID))
40
41
42 ;;; @ variables
43 ;;;
44
45 (defvar eword-field-encoding-method-alist
46   '(("X-Nsubject" . iso-2022-jp-2)
47     ("Newsgroups" . nil)
48     (t            . mime)
49     )
50   "*Alist to specify field encoding method.
51 Its key is field-name, value is encoding method.
52
53 If method is `mime', this field will be encoded into MIME format.
54
55 If method is a MIME-charset, this field will be encoded as the charset
56 when it must be convert into network-code.
57
58 If method is `default-mime-charset', this field will be encoded as
59 variable `default-mime-charset' when it must be convert into
60 network-code.
61
62 If method is nil, this field will not be encoded.")
63
64 (defvar eword-generate-X-Nsubject nil
65   "*If it is not nil, X-Nsubject field is generated
66 when Subject field is encoded by `eword-encode-message-header'.")
67
68 (defvar eword-charset-encoding-alist
69   '((us-ascii           . nil)
70     (iso-8859-1         . "Q")
71     (iso-8859-2         . "Q")
72     (iso-8859-3         . "Q")
73     (iso-8859-4         . "Q")
74     (iso-8859-5         . "Q")
75     (koi8-r             . "Q")
76     (iso-8859-7         . "Q")
77     (iso-8859-8         . "Q")
78     (iso-8859-9         . "Q")
79     (iso-2022-jp        . "B")
80     (iso-2022-kr        . "B")
81     (gb2312             . "B")
82     (cn-gb              . "B")
83     (cn-gb-2312         . "B")
84     (euc-kr             . "B")
85     (iso-2022-jp-2      . "B")
86     (iso-2022-int-1     . "B")
87     ))
88
89
90 ;;; @ encoded-text encoder
91 ;;;
92
93 (defun tm-eword::encode-encoded-text (charset encoding string &optional mode)
94   (let ((text
95          (cond ((string= encoding "B")
96                 (base64-encode-string string))
97                ((string= encoding "Q")
98                 (q-encoding-encode-string string mode))
99                )
100          ))
101     (if text
102         (concat "=?" (upcase (symbol-name charset)) "?"
103                 encoding "?" text "?=")
104       )))
105
106
107 ;;; @ leading char
108 ;;;
109
110 (defun tm-eword::char-type (chr)
111   (if (or (= chr 32)(= chr ?\t))
112       nil
113     (char-charset chr)
114     ))
115
116 (defun tm-eword::parse-lc-word (str)
117   (let* ((chr (sref str 0))
118          (lc (tm-eword::char-type chr))
119          (i (char-length chr))
120          (len (length str))
121          )
122     (while (and (< i len)
123                 (setq chr (sref str i))
124                 (eq lc (tm-eword::char-type chr))
125                 )
126       (setq i (+ i (char-length chr)))
127       )
128     (cons (cons lc (substring str 0 i)) (substring str i))
129     ))
130
131 (defun tm-eword::split-to-lc-words (str)
132   (let (ret dest)
133     (while (and (not (string= str ""))
134                 (setq ret (tm-eword::parse-lc-word str))
135                 )
136       (setq dest (cons (car ret) dest))
137       (setq str (cdr ret))
138       )
139     (reverse dest)
140     ))
141
142
143 ;;; @ word
144 ;;;
145
146 (defun tm-eword::parse-word (lcwl)
147   (let* ((lcw (car lcwl))
148          (lc (car lcw))
149          )
150     (if (null lc)
151         lcwl
152       (let ((lcl (list lc))
153             (str (cdr lcw))
154             )
155         (catch 'tag
156           (while (setq lcwl (cdr lcwl))
157             (setq lcw (car lcwl))
158             (setq lc (car lcw))
159             (if (null lc)
160                 (throw 'tag nil)
161               )
162             (if (not (memq lc lcl))
163                 (setq lcl (cons lc lcl))
164               )
165             (setq str (concat str (cdr lcw)))
166             ))
167         (cons (cons lcl str) lcwl)
168         ))))
169
170 (defun tm-eword::lc-words-to-words (lcwl)
171   (let (ret dest)
172     (while (setq ret (tm-eword::parse-word lcwl))
173       (setq dest (cons (car ret) dest))
174       (setq lcwl (cdr ret))
175       )
176     (reverse dest)
177     ))
178
179
180 ;;; @ rule
181 ;;;
182
183 (defmacro tm-eword::make-rword (text charset encoding type)
184   (` (list (, text)(, charset)(, encoding)(, type))))
185 (defmacro tm-eword::rword-text (rword)
186   (` (car (, rword))))
187 (defmacro tm-eword::rword-charset (rword)
188   (` (car (cdr (, rword)))))
189 (defmacro tm-eword::rword-encoding (rword)
190   (` (car (cdr (cdr (, rword))))))
191 (defmacro tm-eword::rword-type (rword)
192   (` (car (cdr (cdr (cdr (, rword)))))))
193
194 (defun tm-eword::find-charset-rule (charsets)
195   (if charsets
196       (let* ((charset (charsets-to-mime-charset charsets))
197              (encoding (cdr (assq charset eword-charset-encoding-alist)))
198              )
199         (list charset encoding)
200         )))
201
202 (defun tm-eword::words-to-ruled-words (wl &optional mode)
203   (mapcar (function
204            (lambda (word)
205              (let ((ret (tm-eword::find-charset-rule (car word))))
206                (tm-eword::make-rword (cdr word) (car ret)(nth 1 ret) mode)
207                )))
208           wl))
209
210 (defun tm-eword::space-process (seq)
211   (let (prev a ac b c cc)
212     (while seq
213       (setq b (car seq))
214       (setq seq (cdr seq))
215       (setq c (car seq))
216       (setq cc (tm-eword::rword-charset c))
217       (if (null (tm-eword::rword-charset b))
218           (progn
219             (setq a (car prev))
220             (setq ac (tm-eword::rword-charset a))
221             (if (and (tm-eword::rword-encoding a)
222                      (tm-eword::rword-encoding c))
223                 (cond ((eq ac cc)
224                        (setq prev (cons
225                                    (cons (concat (car a)(car b)(car c))
226                                          (cdr a))
227                                    (cdr prev)
228                                    ))
229                        (setq seq (cdr seq))
230                        )
231                       (t
232                        (setq prev (cons
233                                    (cons (concat (car a)(car b))
234                                          (cdr a))
235                                    (cdr prev)
236                                    ))
237                        ))
238               (setq prev (cons b prev))
239               ))
240         (setq prev (cons b prev))
241         ))
242     (reverse prev)
243     ))
244
245 (defun tm-eword::split-string (str &optional mode)
246   (tm-eword::space-process
247    (tm-eword::words-to-ruled-words (tm-eword::lc-words-to-words
248                                     (tm-eword::split-to-lc-words str))
249                                    mode)))
250
251
252 ;;; @ length
253 ;;;
254
255 (defun tm-eword::encoded-word-length (rword)
256   (let ((string   (tm-eword::rword-text     rword))
257         (charset  (tm-eword::rword-charset  rword))
258         (encoding (tm-eword::rword-encoding rword))
259         ret)
260     (setq ret
261           (cond ((string-equal encoding "B")
262                  (setq string (encode-mime-charset-string string charset))
263                  (base64-encoded-length string)
264                  )
265                 ((string-equal encoding "Q")
266                  (setq string (encode-mime-charset-string string charset))
267                  (q-encoding-encoded-length string
268                                             (tm-eword::rword-type rword))
269                  )))
270     (if ret
271         (cons (+ 7 (length (symbol-name charset)) ret) string)
272       )))
273
274
275 ;;; @ encode-string
276 ;;;
277
278 (defun tm-eword::encode-string-1 (column rwl)
279   (let* ((rword (car rwl))
280          (ret (tm-eword::encoded-word-length rword))
281          string len)
282     (if (null ret)
283         (cond ((and (setq string (car rword))
284                     (<= (setq len (+ (length string) column)) 76)
285                     )
286                (setq rwl (cdr rwl))
287                )
288               (t
289                (setq string "\n ")
290                (setq len 1)
291                ))
292       (cond ((and (setq len (car ret))
293                   (<= (+ column len) 76)
294                   )
295              (setq string
296                    (tm-eword::encode-encoded-text
297                     (tm-eword::rword-charset rword)
298                     (tm-eword::rword-encoding rword)
299                     (cdr ret)
300                     (tm-eword::rword-type rword)
301                     ))
302              (setq len (+ (length string) column))
303              (setq rwl (cdr rwl))
304              )
305             (t
306              (setq string (car rword))
307              (let* ((p 0) np
308                     (str "") nstr)
309                (while (and (< p len)
310                            (progn
311                              (setq np (+ p (char-length (sref string p))))
312                              (setq nstr (substring string 0 np))
313                              (setq ret (tm-eword::encoded-word-length
314                                         (cons nstr (cdr rword))
315                                         ))
316                              (setq nstr (cdr ret))
317                              (setq len (+ (car ret) column))
318                              (<= len 76)
319                              ))
320                  (setq str nstr
321                        p np))
322                (if (string-equal str "")
323                    (setq string "\n "
324                          len 1)
325                  (setq rwl (cons (cons (substring string p) (cdr rword))
326                                  (cdr rwl)))
327                  (setq string
328                        (tm-eword::encode-encoded-text
329                         (tm-eword::rword-charset rword)
330                         (tm-eword::rword-encoding rword)
331                         str
332                         (tm-eword::rword-type rword)))
333                  (setq len (+ (length string) column))
334                  )
335                )))
336       )
337     (list string len rwl)
338     ))
339
340 (defun tm-eword::encode-rwl (column rwl)
341   (let (ret dest ps special str ew-f pew-f)
342     (while rwl
343       (setq ew-f (nth 2 (car rwl)))
344       (if (and pew-f ew-f)
345           (setq rwl (cons '(" ") rwl)
346                 pew-f nil)
347         (setq pew-f ew-f)
348         )
349       (setq ret (tm-eword::encode-string-1 column rwl))
350       (setq str (car ret))
351       (if (eq (elt str 0) ?\n)
352           (if (eq special ?\()
353               (progn
354                 (setq dest (concat dest "\n ("))
355                 (setq ret (tm-eword::encode-string-1 2 rwl))
356                 (setq str (car ret))
357                 ))
358         (cond ((eq special 32)
359                (if (string= str "(")
360                    (setq ps t)
361                  (setq dest (concat dest " "))
362                  (setq ps nil)
363                  ))
364               ((eq special ?\()
365                (if ps
366                    (progn
367                      (setq dest (concat dest " ("))
368                      (setq ps nil)
369                      )
370                  (setq dest (concat dest "("))
371                  )
372                )))
373       (cond ((string= str " ")
374              (setq special 32)
375              )
376             ((string= str "(")
377              (setq special ?\()
378              )
379             (t
380              (setq special nil)
381              (setq dest (concat dest str))
382              ))
383       (setq column (nth 1 ret)
384             rwl (nth 2 ret))
385       )
386     (list dest column)
387     ))
388
389 (defun tm-eword::encode-string (column str &optional mode)
390   (tm-eword::encode-rwl column (tm-eword::split-string str mode))
391   )
392
393
394 ;;; @ converter
395 ;;;
396
397 (defun tm-eword::phrase-to-rwl (phrase)
398   (let (token type dest str)
399     (while phrase
400       (setq token (car phrase))
401       (setq type (car token))
402       (cond ((eq type 'quoted-string)
403              (setq str (concat "\"" (cdr token) "\""))
404              (setq dest
405                    (append dest
406                            (list
407                             (let ((ret (tm-eword::find-charset-rule
408                                         (find-non-ascii-charset-string str))))
409                               (tm-eword::make-rword
410                                str (car ret)(nth 1 ret) 'phrase)
411                               )
412                             )))
413              )
414             ((eq type 'comment)
415              (setq dest
416                    (append dest
417                            '(("(" nil nil))
418                            (tm-eword::words-to-ruled-words
419                             (tm-eword::lc-words-to-words
420                              (tm-eword::split-to-lc-words (cdr token)))
421                             'comment)
422                            '((")" nil nil))
423                            ))
424              )
425             (t
426              (setq dest (append dest
427                                 (tm-eword::words-to-ruled-words
428                                  (tm-eword::lc-words-to-words
429                                   (tm-eword::split-to-lc-words (cdr token))
430                                   ) 'phrase)))
431              ))
432       (setq phrase (cdr phrase))
433       )
434     (tm-eword::space-process dest)
435     ))
436
437 (defun tm-eword::phrase-route-addr-to-rwl (phrase-route-addr)
438   (if (eq (car phrase-route-addr) 'phrase-route-addr)
439       (let ((phrase (nth 1 phrase-route-addr))
440             (route (nth 2 phrase-route-addr))
441             dest)
442         (if (eq (car (car phrase)) 'spaces)
443             (setq phrase (cdr phrase))
444           )
445         (setq dest (tm-eword::phrase-to-rwl phrase))
446         (if dest
447             (setq dest (append dest '((" " nil nil))))
448           )
449         (append
450          dest
451          (list (list (concat "<" (std11-addr-to-string route) ">") nil nil))
452          ))))
453
454 (defun tm-eword::addr-spec-to-rwl (addr-spec)
455   (if (eq (car addr-spec) 'addr-spec)
456       (list (list (std11-addr-to-string (cdr addr-spec)) nil nil))
457     ))
458
459 (defun tm-eword::mailbox-to-rwl (mbox)
460   (let ((addr (nth 1 mbox))
461         (comment (nth 2 mbox))
462         dest)
463     (setq dest (or (tm-eword::phrase-route-addr-to-rwl addr)
464                    (tm-eword::addr-spec-to-rwl addr)
465                    ))
466     (if comment
467         (setq dest
468               (append dest
469                       '((" " nil nil)
470                         ("(" nil nil))
471                       (tm-eword::split-string comment 'comment)
472                       '((")" nil nil))
473                       )))
474     dest))
475
476 (defun tm-eword::addresses-to-rwl (addresses)
477   (let ((dest (tm-eword::mailbox-to-rwl (car addresses))))
478     (if dest
479         (while (setq addresses (cdr addresses))
480           (setq dest (append dest
481                              '(("," nil nil))
482                              '((" " nil nil))
483                              (tm-eword::mailbox-to-rwl (car addresses))
484                              ))
485           ))
486     dest))
487
488 (defun tm-eword::encode-address-list (column str)
489   (tm-eword::encode-rwl
490    column
491    (tm-eword::addresses-to-rwl (std11-parse-addresses-string str))
492    ))
493
494
495 ;;; @ application interfaces
496 ;;;
497
498 (defun eword-encode-field (str)
499   (setq str (std11-unfold-string str))
500   (let ((ret (string-match std11-field-head-regexp str)))
501     (or (if ret
502             (let ((field-name (substring str 0 (1- (match-end 0))))
503                   (field-body (eliminate-top-spaces
504                                (substring str (match-end 0))))
505                   fname)
506               (if (setq ret
507                         (cond ((string-equal field-body "") "")
508                               ((member (setq fname (downcase field-name))
509                                        '("reply-to" "from" "sender"
510                                          "resent-reply-to" "resent-from"
511                                          "resent-sender" "to" "resent-to"
512                                          "cc" "resent-cc"
513                                          "bcc" "resent-bcc" "dcc")
514                                        )
515                                (car (tm-eword::encode-address-list
516                                      (+ (length field-name) 2) field-body))
517                                )
518                               (t
519                                (car (tm-eword::encode-string
520                                      (+ (length field-name) 1)
521                                      field-body 'text))
522                                ))
523                         )
524                   (concat field-name ": " ret)
525                 )))
526         (car (tm-eword::encode-string 0 str))
527         )))
528
529 (defun mime/exist-encoded-word-in-subject ()
530   (let ((str (std11-field-body "Subject")))
531     (if (and str (string-match mime/encoded-word-regexp str))
532         str)))
533
534 (defun eword-encode-message-header (&optional code-conversion)
535   (interactive "*")
536   (save-excursion
537     (save-restriction
538       (std11-narrow-to-header mail-header-separator)
539       (goto-char (point-min))
540       (let ((default-cs (mime-charset-to-coding-system default-mime-charset))
541             beg end field-name)
542         (while (re-search-forward std11-field-head-regexp nil t)
543           (setq beg (match-beginning 0))
544           (setq field-name (buffer-substring beg (1- (match-end 0))))
545           (setq end (std11-field-end))
546           (and (find-non-ascii-charset-region beg end)
547                (let ((ret (or (ASSOC (downcase field-name)
548                                      eword-field-encoding-method-alist
549                                      :test (function
550                                             (lambda (str1 str2)
551                                               (and (stringp str2)
552                                                    (string= str1
553                                                             (downcase str2))
554                                                    ))))
555                               (assq t eword-field-encoding-method-alist)
556                               )))
557                  (if ret
558                      (let ((method (cdr ret)))
559                        (cond ((eq method 'mime)
560                               (let ((field
561                                      (buffer-substring-no-properties beg end)
562                                      ))
563                                 (delete-region beg end)
564                                 (insert (eword-encode-field field))
565                                 ))
566                              (code-conversion
567                               (let ((cs
568                                      (or (mime-charset-to-coding-system
569                                           method)
570                                          default-cs)))
571                                 (encode-coding-region beg end cs)
572                                 )))
573                        ))
574                  ))
575           ))
576       (and eword-generate-X-Nsubject
577            (or (std11-field-body "X-Nsubject")
578                (let ((str (mime/exist-encoded-word-in-subject)))
579                  (if str
580                      (progn
581                        (setq str
582                              (eword-decode-string
583                               (std11-unfold-string str)))
584                        (if code-conversion
585                            (setq str
586                                  (encode-mime-charset-string
587                                   str
588                                   (or (cdr (ASSOC
589                                             "x-nsubject"
590                                             eword-field-encoding-method-alist
591                                             :test
592                                             (function
593                                              (lambda (str1 str2)
594                                                (and (stringp str2)
595                                                     (string= str1
596                                                              (downcase str2))
597                                                     )))))
598                                       'iso-2022-jp-2)))
599                          )
600                        (insert (concat "\nX-Nsubject: " str))
601                        )))))
602       )))
603
604 (defun eword-encode-string (str &optional column mode)
605   (car (tm-eword::encode-rwl (or column 0) (tm-eword::split-string str mode)))
606   )
607
608
609 ;;; @ end
610 ;;;
611
612 (provide 'eword-encode)
613
614 ;;; eword-encode.el ends here