update.
[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 'mime-def)
28 (require 'mel)
29 (require 'std11)
30 (require 'eword-decode)
31
32
33 ;;; @ variables
34 ;;;
35
36 (defgroup eword-encode nil
37   "Encoded-word encoding"
38   :group 'mime)
39
40 (defcustom eword-field-encoding-method-alist
41   '(("X-Nsubject" . iso-2022-jp-2)
42     ("Newsgroups" . nil)
43     ("Message-ID" . nil)
44     (t            . mime)
45     )
46   "*Alist to specify field encoding method.
47 Its key is field-name, value is encoding method.
48
49 If method is `mime', this field will be encoded into MIME format.
50
51 If method is a MIME-charset, this field will be encoded as the charset
52 when it must be convert into network-code.
53
54 If method is `default-mime-charset', this field will be encoded as
55 variable `default-mime-charset' when it must be convert into
56 network-code.
57
58 If method is nil, this field will not be encoded."
59   :group 'eword-encode
60   :type '(repeat (cons (choice :tag "Field"
61                                (string :tag "Name")
62                                (const :tag "Default" t))
63                        (choice :tag "Method"
64                                (const :tag "MIME conversion" mime)
65                                (symbol :tag "non-MIME conversion")
66                                (const :tag "no-conversion" nil)))))
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     (tis-620            . "B")
86     (iso-2022-jp-2      . "B")
87     (iso-2022-int-1     . "B")
88     (utf-8              . "B")
89     ))
90
91
92 ;;; @ encoded-text encoder
93 ;;;
94
95 (defun eword-encode-text (charset encoding string &optional mode)
96   "Encode STRING as an encoded-word, and return the result.
97 CHARSET is a symbol to indicate MIME charset of the encoded-word.
98 ENCODING allows \"B\" or \"Q\".
99 MODE is allows `text', `comment', `phrase' or nil.  Default value is
100 `phrase'."
101   (let ((text (encoded-text-encode-string string encoding)))
102     (if text
103         (concat "=?" (upcase (symbol-name charset)) "?"
104                 encoding "?" text "?=")
105       )))
106
107
108 ;;; @ charset word
109 ;;;
110
111 (defsubst eword-encode-char-type (character)
112   (if (memq character '(?  ?\t ?\n))
113       nil
114     (char-charset character)
115     ))
116
117 (defun eword-encode-divide-into-charset-words (string)
118   (let ((len (length string))
119         dest)
120     (while (> len 0)
121       (let* ((chr (sref string 0))
122              (charset (eword-encode-char-type chr))
123              (i (char-length chr)))
124         (while (and (< i len)
125                     (setq chr (sref string i))
126                     (eq charset (eword-encode-char-type chr))
127                     )
128           (setq i (char-next-index chr i))
129           )
130         (setq dest (cons (cons charset (substring string 0 i)) dest)
131               string (substring string i)
132               len (- len i)
133               )))
134     (nreverse dest)
135     ))
136
137
138 ;;; @ word
139 ;;;
140
141 (defun eword-encode-charset-words-to-words (charset-words)
142   (let (dest)
143     (while charset-words
144       (let* ((charset-word (car charset-words))
145              (charset (car charset-word))
146              )
147         (if charset
148             (let ((charsets (list charset))
149                   (str (cdr charset-word))
150                   )
151               (catch 'tag
152                 (while (setq charset-words (cdr charset-words))
153                   (setq charset-word (car charset-words)
154                         charset (car charset-word))
155                   (if (null charset)
156                       (throw 'tag nil)
157                     )
158                   (or (memq charset charsets)
159                       (setq charsets (cons charset charsets))
160                       )
161                   (setq str (concat str (cdr charset-word)))
162                   ))
163               (setq dest (cons (cons charsets str) dest))
164               )
165           (setq dest (cons charset-word dest)
166                 charset-words (cdr charset-words)
167                 ))))
168     (nreverse dest)
169     ))
170
171
172 ;;; @ rule
173 ;;;
174
175 (defmacro make-ew-rword (text charset encoding type)
176   (` (list (, text)(, charset)(, encoding)(, type))))
177 (defmacro ew-rword-text (rword)
178   (` (car (, rword))))
179 (defmacro ew-rword-charset (rword)
180   (` (car (cdr (, rword)))))
181 (defmacro ew-rword-encoding (rword)
182   (` (car (cdr (cdr (, rword))))))
183 (defmacro ew-rword-type (rword)
184   (` (car (cdr (cdr (cdr (, rword)))))))
185
186 (defun ew-find-charset-rule (charsets)
187   (if charsets
188       (let* ((charset (find-mime-charset-by-charsets charsets))
189              (encoding (cdr (or (assq charset eword-charset-encoding-alist)
190                                 '(nil . "Q")))))
191         (list charset encoding)
192         )))
193
194 (defun tm-eword::words-to-ruled-words (wl &optional mode)
195   (mapcar (function
196            (lambda (word)
197              (let ((ret (ew-find-charset-rule (car word))))
198                (make-ew-rword (cdr word) (car ret)(nth 1 ret) mode)
199                )))
200           wl))
201
202 (defun ew-space-process (seq)
203   (let (prev a ac b c cc)
204     (while seq
205       (setq b (car seq))
206       (setq seq (cdr seq))
207       (setq c (car seq))
208       (setq cc (ew-rword-charset c))
209       (if (and (null (ew-rword-charset b))
210                (not (eq (ew-rword-type b) 'special)))
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   (ew-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 ew-encode-rword-1 (column rwl &optional must-output)
272   (catch 'can-not-output
273     (let* ((rword (car rwl))
274            (ret (tm-eword::encoded-word-length rword))
275            string len)
276       (if (null ret)
277           (cond ((and (setq string (car rword))
278                       (or (<= (setq len (+ (length string) column)) 76)
279                           (<= column 1))
280                       )
281                  (setq rwl (cdr rwl))
282                  )
283                 ((memq (aref string 0) '(?  ?\t))
284                  (setq string (concat "\n" string)
285                        len (length string)
286                        rwl (cdr rwl))
287                  )
288                 (must-output
289                  (setq string "\n "
290                        len 1)
291                  )
292                 (t
293                  (throw 'can-not-output nil)
294                  ))
295         (cond ((and (setq len (car ret))
296                     (<= (+ column len) 76)
297                     )
298                (setq string
299                      (eword-encode-text
300                       (ew-rword-charset rword)
301                       (ew-rword-encoding rword)
302                       (cdr ret)
303                       (ew-rword-type rword)
304                       ))
305                (setq len (+ (length string) column))
306                (setq rwl (cdr rwl))
307                )
308               (t
309                (setq string (car rword))
310                (let* ((p 0) np
311                       (str "") nstr)
312                  (while (and (< p len)
313                              (progn
314                                (setq np (char-next-index (sref string p) p))
315                                (setq nstr (substring string 0 np))
316                                (setq ret (tm-eword::encoded-word-length
317                                           (cons nstr (cdr rword))
318                                           ))
319                                (setq nstr (cdr ret))
320                                (setq len (+ (car ret) column))
321                                (<= len 76)
322                                ))
323                    (setq str nstr
324                          p np))
325                  (if (string-equal str "")
326                      (if must-output
327                          (setq string "\n "
328                                len 1)
329                        (throw 'can-not-output nil))
330                    (setq rwl (cons (cons (substring string p) (cdr rword))
331                                    (cdr rwl)))
332                    (setq string
333                          (eword-encode-text
334                           (ew-rword-charset rword)
335                           (ew-rword-encoding rword)
336                           str
337                           (ew-rword-type rword)))
338                    (setq len (+ (length string) column))
339                    )
340                  )))
341         )
342       (list string len rwl)
343       )))
344
345 (defun eword-encode-rword-list (column rwl)
346   (let (ret dest str ew-f pew-f folded-points)
347     (while rwl
348       (setq ew-f (nth 2 (car rwl)))
349       (if (and pew-f ew-f)
350           (setq rwl (cons '(" ") rwl)
351                 pew-f nil)
352         (setq pew-f ew-f)
353         )
354       (if (null (setq ret (ew-encode-rword-1 column rwl)))
355           (let ((i (1- (length dest)))
356                 c s r-dest r-column)
357             (catch 'success
358               (while (catch 'found
359                        (while (>= i 0)
360                          (cond ((memq (setq c (aref dest i)) '(?  ?\t))
361                                 (if (memq i folded-points)
362                                     (throw 'found nil)
363                                   (setq folded-points (cons i folded-points))
364                                   (throw 'found i))
365                                 )
366                                ((eq c ?\n)
367                                 (throw 'found nil)
368                                 ))
369                          (setq i (1- i))))
370                 (setq s (substring dest i)
371                       r-column (length s)
372                       r-dest (concat (substring dest 0 i) "\n" s))
373                 (when (setq ret (ew-encode-rword-1 r-column rwl))
374                   (setq dest r-dest
375                         column r-column)
376                   (throw 'success t)
377                   ))
378               (setq ret (ew-encode-rword-1 column rwl 'must-output))
379               )))
380       (setq str (car ret))
381       (setq dest (concat dest str))
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 (ew-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 special))
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 special))
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     (ew-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