Merge flim-1_12_6.
[elisp/flim.git] / eword-encode.el
1 ;;; eword-encode.el --- RFC 2047 based encoded-word encoder for GNU Emacs
2
3 ;; Copyright (C) 1995,1996,1997,1998,1999 Free Software Foundation, Inc.
4
5 ;; Author: MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; Keywords: encoded-word, MIME, multilingual, header, mail, news
7
8 ;; This file is part of FLIM (Faithful Library about Internet Message).
9
10 ;; This program is free software; you can redistribute it and/or
11 ;; modify it under the terms of the GNU General Public License as
12 ;; published by the Free Software Foundation; either version 2, or (at
13 ;; your option) any later version.
14
15 ;; This program is distributed in the hope that it will be useful, but
16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 ;; General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Code:
26
27 (require 'poem)
28 (require 'mel)
29 (require 'std11)
30 (require 'mime-def)
31 (require 'eword-decode)
32
33
34 ;;; @ variables
35 ;;;
36
37 (defgroup eword-encode nil
38   "Encoded-word encoding"
39   :group 'mime)
40
41 (defcustom eword-field-encoding-method-alist
42   '(("X-Nsubject" . iso-2022-jp-2)
43     ("Newsgroups" . nil)
44     ("Message-ID" . nil)
45     (t            . mime)
46     )
47   "*Alist to specify field encoding method.
48 Its key is field-name, value is encoding method.
49
50 If method is `mime', this field will be encoded into MIME format.
51
52 If method is a MIME-charset, this field will be encoded as the charset
53 when it must be convert into network-code.
54
55 If method is `default-mime-charset', this field will be encoded as
56 variable `default-mime-charset' when it must be convert into
57 network-code.
58
59 If method is nil, this field will not be encoded."
60   :group 'eword-encode
61   :type '(repeat (cons (choice :tag "Field"
62                                (string :tag "Name")
63                                (const :tag "Default" t))
64                        (choice :tag "Method"
65                                (const :tag "MIME conversion" mime)
66                                (symbol :tag "non-MIME conversion")
67                                (const :tag "no-conversion" nil)))))
68
69 (defvar eword-charset-encoding-alist
70   '((us-ascii           . nil)
71     (iso-8859-1         . "Q")
72     (iso-8859-2         . "Q")
73     (iso-8859-3         . "Q")
74     (iso-8859-4         . "Q")
75     (iso-8859-5         . "Q")
76     (koi8-r             . "Q")
77     (iso-8859-7         . "Q")
78     (iso-8859-8         . "Q")
79     (iso-8859-9         . "Q")
80     (iso-2022-jp        . "B")
81     (iso-2022-kr        . "B")
82     (gb2312             . "B")
83     (cn-gb              . "B")
84     (cn-gb-2312         . "B")
85     (euc-kr             . "B")
86     (tis-620            . "B")
87     (iso-2022-jp-2      . "B")
88     (iso-2022-int-1     . "B")
89     (utf-8              . "B")
90     ))
91
92
93 ;;; @ encoded-text encoder
94 ;;;
95
96 (defun eword-encode-text (charset encoding string &optional mode)
97   "Encode STRING as an encoded-word, and return the result.
98 CHARSET is a symbol to indicate MIME charset of the encoded-word.
99 ENCODING allows \"B\" or \"Q\".
100 MODE is allows `text', `comment', `phrase' or nil.  Default value is
101 `phrase'."
102   (let ((text (encoded-text-encode-string string encoding)))
103     (if text
104         (concat "=?" (upcase (symbol-name charset)) "?"
105                 encoding "?" text "?=")
106       )))
107
108
109 ;;; @ charset word
110 ;;;
111
112 (defsubst eword-encode-char-type (character)
113   (if (memq character '(?  ?\t ?\n))
114       nil
115     (char-charset character)
116     ))
117
118 (defun eword-encode-divide-into-charset-words (string)
119   (let ((len (length string))
120         dest)
121     (while (> len 0)
122       (let* ((chr (sref string 0))
123              (charset (eword-encode-char-type chr))
124              (i (char-length chr)))
125         (while (and (< i len)
126                     (setq chr (sref string i))
127                     (eq charset (eword-encode-char-type chr))
128                     )
129           (setq i (char-next-index chr i))
130           )
131         (setq dest (cons (cons charset (substring string 0 i)) dest)
132               string (substring string i)
133               len (- len i)
134               )))
135     (nreverse dest)
136     ))
137
138
139 ;;; @ word
140 ;;;
141
142 (defun eword-encode-charset-words-to-words (charset-words)
143   (let (dest)
144     (while charset-words
145       (let* ((charset-word (car charset-words))
146              (charset (car charset-word))
147              )
148         (if charset
149             (let ((charsets (list charset))
150                   (str (cdr charset-word))
151                   )
152               (catch 'tag
153                 (while (setq charset-words (cdr charset-words))
154                   (setq charset-word (car charset-words)
155                         charset (car charset-word))
156                   (if (null charset)
157                       (throw 'tag nil)
158                     )
159                   (or (memq charset charsets)
160                       (setq charsets (cons charset charsets))
161                       )
162                   (setq str (concat str (cdr charset-word)))
163                   ))
164               (setq dest (cons (cons charsets str) dest))
165               )
166           (setq dest (cons charset-word dest)
167                 charset-words (cdr charset-words)
168                 ))))
169     (nreverse dest)
170     ))
171
172
173 ;;; @ rule
174 ;;;
175
176 (defmacro make-ew-rword (text charset encoding type)
177   (` (list (, text)(, charset)(, encoding)(, type))))
178 (defmacro ew-rword-text (rword)
179   (` (car (, rword))))
180 (defmacro ew-rword-charset (rword)
181   (` (car (cdr (, rword)))))
182 (defmacro ew-rword-encoding (rword)
183   (` (car (cdr (cdr (, rword))))))
184 (defmacro ew-rword-type (rword)
185   (` (car (cdr (cdr (cdr (, rword)))))))
186
187 (defun tm-eword::find-charset-rule (charsets)
188   (if charsets
189       (let* ((charset (charsets-to-mime-charset charsets))
190              (encoding (cdr (assq charset eword-charset-encoding-alist)))
191              )
192         (list charset encoding)
193         )))
194
195 (defun tm-eword::words-to-ruled-words (wl &optional mode)
196   (mapcar (function
197            (lambda (word)
198              (let ((ret (tm-eword::find-charset-rule (car word))))
199                (make-ew-rword (cdr word) (car ret)(nth 1 ret) mode)
200                )))
201           wl))
202
203 (defun tm-eword::space-process (seq)
204   (let (prev a ac b c cc)
205     (while seq
206       (setq b (car seq))
207       (setq seq (cdr seq))
208       (setq c (car seq))
209       (setq cc (ew-rword-charset c))
210       (if (null (ew-rword-charset b))
211           (progn
212             (setq a (car prev))
213             (setq ac (ew-rword-charset a))
214             (if (and (ew-rword-encoding a)
215                      (ew-rword-encoding c))
216                 (cond ((eq ac cc)
217                        (setq prev (cons
218                                    (cons (concat (car a)(car b)(car c))
219                                          (cdr a))
220                                    (cdr prev)
221                                    ))
222                        (setq seq (cdr seq))
223                        )
224                       (t
225                        (setq prev (cons
226                                    (cons (concat (car a)(car b))
227                                          (cdr a))
228                                    (cdr prev)
229                                    ))
230                        ))
231               (setq prev (cons b prev))
232               ))
233         (setq prev (cons b prev))
234         ))
235     (reverse prev)
236     ))
237
238 (defun eword-encode-split-string (str &optional mode)
239   (tm-eword::space-process
240    (tm-eword::words-to-ruled-words
241     (eword-encode-charset-words-to-words
242      (eword-encode-divide-into-charset-words str))
243     mode)))
244
245
246 ;;; @ length
247 ;;;
248
249 (defun tm-eword::encoded-word-length (rword)
250   (let ((string   (ew-rword-text     rword))
251         (charset  (ew-rword-charset  rword))
252         (encoding (ew-rword-encoding rword))
253         ret)
254     (setq ret
255           (cond ((string-equal encoding "B")
256                  (setq string (encode-mime-charset-string string charset))
257                  (base64-encoded-length string)
258                  )
259                 ((string-equal encoding "Q")
260                  (setq string (encode-mime-charset-string string charset))
261                  (Q-encoded-text-length string (ew-rword-type rword))
262                  )))
263     (if ret
264         (cons (+ 7 (length (symbol-name charset)) ret) string)
265       )))
266
267
268 ;;; @ encode-string
269 ;;;
270
271 (defun tm-eword::encode-string-1 (column rwl)
272   (let* ((rword (car rwl))
273          (ret (tm-eword::encoded-word-length rword))
274          string len)
275     (if (null ret)
276         (cond ((and (setq string (car rword))
277                     (or (<= (setq len (+ (length string) column)) 76)
278                         (<= column 1))
279                     )
280                (setq rwl (cdr rwl))
281                )
282               (t
283                (setq string "\n ")
284                (setq len 1)
285                ))
286       (cond ((and (setq len (car ret))
287                   (<= (+ column len) 76)
288                   )
289              (setq string
290                    (eword-encode-text
291                     (ew-rword-charset rword)
292                     (ew-rword-encoding rword)
293                     (cdr ret)
294                     (ew-rword-type rword)
295                     ))
296              (setq len (+ (length string) column))
297              (setq rwl (cdr rwl))
298              )
299             (t
300              (setq string (car rword))
301              (let* ((p 0) np
302                     (str "") nstr)
303                (while (and (< p len)
304                            (progn
305                              (setq np (char-next-index (sref string p) p))
306                              (setq nstr (substring string 0 np))
307                              (setq ret (tm-eword::encoded-word-length
308                                         (cons nstr (cdr rword))
309                                         ))
310                              (setq nstr (cdr ret))
311                              (setq len (+ (car ret) column))
312                              (<= len 76)
313                              ))
314                  (setq str nstr
315                        p np))
316                (if (string-equal str "")
317                    (setq string "\n "
318                          len 1)
319                  (setq rwl (cons (cons (substring string p) (cdr rword))
320                                  (cdr rwl)))
321                  (setq string
322                        (eword-encode-text
323                         (ew-rword-charset rword)
324                         (ew-rword-encoding rword)
325                         str
326                         (ew-rword-type rword)))
327                  (setq len (+ (length string) column))
328                  )
329                )))
330       )
331     (list string len rwl)
332     ))
333
334 (defun eword-encode-rword-list (column rwl)
335   (let (ret dest ps special str ew-f pew-f bew)
336     (while rwl
337       (setq ew-f (nth 2 (car rwl)))
338       (if (and pew-f ew-f)
339           (setq rwl (cons '(" ") rwl)
340                 bew t
341                 pew-f nil)
342         (setq pew-f ew-f
343               bew nil)
344         )
345       (setq ret (tm-eword::encode-string-1 column rwl))
346       (setq str (car ret))
347       (if (eq (elt str 0) ?\n)
348           (cond
349            ((eq special ?\()
350             (setq dest (concat dest "\n ("))
351             (setq ret (tm-eword::encode-string-1 2 rwl))
352             (setq str (car ret)))
353            ((eq bew t)
354             (setq dest (concat dest "\n "))
355             (setq ret (tm-eword::encode-string-1 1 (cdr rwl)))
356             (setq str (car ret))))
357         (cond ((eq special ? )
358                (if (string= str "(")
359                    (setq ps t)
360                  (setq dest (concat dest " "))
361                  (setq ps nil)
362                  ))
363               ((eq special ?\()
364                (if ps
365                    (progn
366                      (setq dest (concat dest " ("))
367                      (setq ps nil)
368                      )
369                  (setq dest (concat dest "("))
370                  )
371                )))
372       (cond ((string= str " ")
373              (setq special ? )
374              )
375             ((string= str "(")
376              (setq special ?\()
377              )
378             (t
379              (setq special nil)
380              (setq dest (concat dest str))
381              ))
382       (setq column (nth 1 ret)
383             rwl (nth 2 ret))
384       )
385     (list dest column)
386     ))
387
388
389 ;;; @ converter
390 ;;;
391
392 (defun eword-encode-phrase-to-rword-list (phrase)
393   (let (token type dest str)
394     (while phrase
395       (setq token (car phrase))
396       (setq type (car token))
397       (cond ((eq type 'quoted-string)
398              (setq str (concat "\"" (cdr token) "\""))
399              (setq dest
400                    (append dest
401                            (list
402                             (let ((ret (tm-eword::find-charset-rule
403                                         (find-non-ascii-charset-string str))))
404                               (make-ew-rword
405                                str (car ret)(nth 1 ret) 'phrase)
406                               )
407                             )))
408              )
409             ((eq type 'comment)
410              (setq dest
411                    (append dest
412                            '(("(" nil nil))
413                            (tm-eword::words-to-ruled-words
414                             (eword-encode-charset-words-to-words
415                              (eword-encode-divide-into-charset-words
416                               (cdr token)))
417                             'comment)
418                            '((")" nil nil))
419                            ))
420              )
421             (t
422              (setq dest
423                    (append dest
424                            (tm-eword::words-to-ruled-words
425                             (eword-encode-charset-words-to-words
426                              (eword-encode-divide-into-charset-words
427                               (cdr token))
428                              ) 'phrase)))
429              ))
430       (setq phrase (cdr phrase))
431       )
432     (tm-eword::space-process dest)
433     ))
434
435 (defun eword-encode-addr-seq-to-rword-list (seq)
436   (let (dest pname)
437     (while seq
438       (let* ((token (car seq))
439              (name (car token))
440              )
441         (cond ((eq name 'spaces)
442                (setq dest (nconc dest (list (list (cdr token) nil nil))))
443                )
444               ((eq name 'comment)
445                (setq dest
446                      (nconc
447                       dest
448                       (list (list "(" nil nil))
449                       (eword-encode-split-string (cdr token) 'comment)
450                       (list (list ")" nil nil))
451                       ))
452                )
453               ((eq name 'quoted-string)
454                (setq dest
455                      (nconc
456                       dest
457                       (list
458                        (list (concat "\"" (cdr token) "\"") nil nil)
459                        )))
460                )
461               (t
462                (setq dest
463                      (if (or (eq pname 'spaces)
464                              (eq pname 'comment))
465                          (nconc dest (list (list (cdr token) nil nil)))
466                        (nconc (butlast dest)
467                               (list
468                                (list (concat (car (car (last dest)))
469                                              (cdr token))
470                                      nil nil)))))
471                ))
472         (setq seq (cdr seq)
473               pname name))
474       )
475     dest))
476
477 (defun eword-encode-phrase-route-addr-to-rword-list (phrase-route-addr)
478   (if (eq (car phrase-route-addr) 'phrase-route-addr)
479       (let ((phrase (nth 1 phrase-route-addr))
480             (route (nth 2 phrase-route-addr))
481             dest)
482         ;; (if (eq (car (car phrase)) 'spaces)
483         ;;     (setq phrase (cdr phrase))
484         ;;   )
485         (setq dest (eword-encode-phrase-to-rword-list phrase))
486         (if dest
487             (setq dest (append dest '((" " nil nil))))
488           )
489         (append
490          dest
491          (eword-encode-addr-seq-to-rword-list
492           (append '((specials . "<"))
493                   route
494                   '((specials . ">"))))
495          ))))
496
497 (defun eword-encode-addr-spec-to-rword-list (addr-spec)
498   (if (eq (car addr-spec) 'addr-spec)
499       (eword-encode-addr-seq-to-rword-list (cdr addr-spec))
500     ))
501
502 (defun eword-encode-mailbox-to-rword-list (mbox)
503   (let ((addr (nth 1 mbox))
504         (comment (nth 2 mbox))
505         dest)
506     (setq dest (or (eword-encode-phrase-route-addr-to-rword-list addr)
507                    (eword-encode-addr-spec-to-rword-list addr)
508                    ))
509     (if comment
510         (setq dest
511               (append dest
512                       '((" " nil nil)
513                         ("(" nil nil))
514                       (eword-encode-split-string comment 'comment)
515                       (list '(")" nil nil))
516                       )))
517     dest))
518
519 (defsubst eword-encode-addresses-to-rword-list (addresses)
520   (let ((dest (eword-encode-mailbox-to-rword-list (car addresses))))
521     (if dest
522         (while (setq addresses (cdr addresses))
523           (setq dest
524                 (nconc dest
525                        (list '("," nil nil))
526                        ;; (list '(" " nil nil))
527                        (eword-encode-mailbox-to-rword-list (car addresses))
528                        ))
529           ))
530     dest))
531
532 (defsubst eword-encode-msg-id-to-rword-list (msg-id)
533   (list
534    (list
535     (concat "<"
536             (caar (eword-encode-addr-seq-to-rword-list (cdr msg-id)))
537             ">")
538     nil nil)))
539
540 (defsubst eword-encode-in-reply-to-to-rword-list (in-reply-to)
541   (let (dest)
542     (while in-reply-to
543       (setq dest
544             (append dest
545                     (let ((elt (car in-reply-to)))
546                       (if (eq (car elt) 'phrase)
547                           (eword-encode-phrase-to-rword-list (cdr elt))
548                         (eword-encode-msg-id-to-rword-list elt)
549                         ))))
550       (setq in-reply-to (cdr in-reply-to)))
551     dest))
552
553
554 ;;; @ application interfaces
555 ;;;
556
557 (defcustom eword-encode-default-start-column 10
558   "Default start column if it is omitted."
559   :group 'eword-encode
560   :type 'integer)
561
562 (defun eword-encode-string (string &optional column mode)
563   "Encode STRING as encoded-words, and return the result.
564 Optional argument COLUMN is start-position of the field.
565 Optional argument MODE allows `text', `comment', `phrase' or nil.
566 Default value is `phrase'."
567   (car (eword-encode-rword-list
568         (or column eword-encode-default-start-column)
569         (eword-encode-split-string string mode))))
570
571 (defun eword-encode-address-list (string &optional column)
572   "Encode header field STRING as list of address, and return the result.
573 Optional argument COLUMN is start-position of the field."
574   (car (eword-encode-rword-list
575         (or column eword-encode-default-start-column)
576         (eword-encode-addresses-to-rword-list
577          (std11-parse-addresses-string string))
578         )))
579
580 (defun eword-encode-in-reply-to (string &optional column)
581   "Encode header field STRING as In-Reply-To field, and return the result.
582 Optional argument COLUMN is start-position of the field."
583   (car (eword-encode-rword-list
584         (or column 13)
585         (eword-encode-in-reply-to-to-rword-list
586          (std11-parse-msg-ids-string string)))))
587
588 (defun eword-encode-structured-field-body (string &optional column)
589   "Encode header field STRING as structured field, and return the result.
590 Optional argument COLUMN is start-position of the field."
591   (car (eword-encode-rword-list
592         (or column eword-encode-default-start-column)
593         (eword-encode-addr-seq-to-rword-list (std11-lexical-analyze string))
594         )))
595
596 (defun eword-encode-unstructured-field-body (string &optional column)
597   "Encode header field STRING as unstructured field, and return the result.
598 Optional argument COLUMN is start-position of the field."
599   (car (eword-encode-rword-list
600         (or column eword-encode-default-start-column)
601         (eword-encode-split-string string 'text))))
602
603 (defun eword-encode-field-body (field-body field-name)
604   "Encode FIELD-BODY as FIELD-NAME, and return the result.
605 A lexical token includes non-ASCII character is encoded as MIME
606 encoded-word.  ASCII token is not encoded."
607   (setq field-body (std11-unfold-string field-body))
608   (if (string= field-body "")
609       ""
610     (let (start)
611       (if (symbolp field-name)
612           (setq start (1+ (length (symbol-name field-name))))
613         (setq start (1+ (length field-name))
614               field-name (intern (capitalize field-name))))
615       (cond ((memq field-name
616                    '(Reply-To
617                      From Sender
618                      Resent-Reply-To Resent-From
619                      Resent-Sender To Resent-To
620                      Cc Resent-Cc Bcc Resent-Bcc
621                      Dcc))
622              (eword-encode-address-list field-body start)
623              )
624             ((eq field-name 'In-Reply-To)
625              (eword-encode-in-reply-to field-body start)
626              )
627             ((memq field-name '(Mime-Version User-Agent))
628              (eword-encode-structured-field-body field-body start)
629              )
630             (t
631              (eword-encode-unstructured-field-body field-body start)
632              ))
633       )))
634
635 (defun eword-in-subject-p ()
636   (let ((str (std11-field-body "Subject")))
637     (if (and str (string-match eword-encoded-word-regexp str))
638         str)))
639
640 (defsubst eword-find-field-encoding-method (field-name)
641   (setq field-name (downcase field-name))
642   (let ((alist eword-field-encoding-method-alist))
643     (catch 'found
644       (while alist
645         (let* ((pair (car alist))
646                (str (car pair)))
647           (if (and (stringp str)
648                    (string= field-name (downcase str)))
649               (throw 'found (cdr pair))
650             ))
651         (setq alist (cdr alist)))
652       (cdr (assq t eword-field-encoding-method-alist))
653       )))
654
655 (defun eword-encode-header (&optional code-conversion)
656   "Encode header fields to network representation, such as MIME encoded-word.
657
658 It refer variable `eword-field-encoding-method-alist'."
659   (interactive "*")
660   (save-excursion
661     (save-restriction
662       (std11-narrow-to-header mail-header-separator)
663       (goto-char (point-min))
664       (let ((default-cs (mime-charset-to-coding-system default-mime-charset))
665             bbeg end field-name)
666         (while (re-search-forward std11-field-head-regexp nil t)
667           (setq bbeg (match-end 0)
668                 field-name (buffer-substring (match-beginning 0) (1- bbeg))
669                 end (std11-field-end))
670           (and (find-non-ascii-charset-region bbeg end)
671                (let ((method (eword-find-field-encoding-method
672                               (downcase field-name))))
673                  (cond ((eq method 'mime)
674                         (let ((field-body
675                                (buffer-substring-no-properties bbeg end)
676                                ))
677                           (delete-region bbeg end)
678                           (insert (eword-encode-field-body field-body
679                                                            field-name))
680                           ))
681                        (code-conversion
682                         (let ((cs
683                                (or (mime-charset-to-coding-system
684                                     method)
685                                    default-cs)))
686                           (encode-coding-region bbeg end cs)
687                           )))
688                  ))
689           ))
690       )))
691
692
693 ;;; @ end
694 ;;;
695
696 (provide 'eword-encode)
697
698 ;;; eword-encode.el ends here