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