1 ;;; eword-decode.el --- RFC 2047 based encoded-word decoder for GNU Emacs
3 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004,
4 ;; 2005 Free Software Foundation, Inc.
6 ;; Author: ENAMI Tsugutomo <enami@sys.ptg.sony.co.jp>
7 ;; MORIOKA Tomohiko <tomo@m17n.org>
8 ;; TANAKA Akira <akr@m17n.org>
10 ;; Original: 1992/07/20 ENAMI Tsugutomo's `mime.el'.
11 ;; Renamed: 1993/06/03 to tiny-mime.el by MORIOKA Tomohiko
12 ;; Renamed: 1995/10/03 to tm-ew-d.el (split off encoder)
13 ;; by MORIOKA Tomohiko
14 ;; Renamed: 1997/02/22 from tm-ew-d.el by MORIOKA Tomohiko
15 ;; Keywords: encoded-word, MIME, multilingual, header, mail, news
17 ;; This file is part of FLIM (Faithful Library about Internet Message).
19 ;; This program is free software; you can redistribute it and/or
20 ;; modify it under the terms of the GNU General Public License as
21 ;; published by the Free Software Foundation; either version 2, or (at
22 ;; your option) any later version.
24 ;; This program is distributed in the hope that it will be useful, but
25 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
26 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27 ;; General Public License for more details.
29 ;; You should have received a copy of the GNU General Public License
30 ;; along with GNU Emacs; see the file COPYING. If not, write to the
31 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
32 ;; Boston, MA 02110-1301, USA.
40 (eval-when-compile (require 'cl)) ; list*, pop
46 ;; User options are defined in mime-def.el.
49 ;;; @ MIME encoded-word definition
53 (defconst eword-encoded-text-regexp "[!->@-~]+")
55 (defconst eword-encoded-word-regexp
57 (concat (regexp-quote "=?")
59 mime-charset-regexp ; 1
63 mime-language-regexp ; 2
67 mime-encoding-regexp ; 3
71 eword-encoded-text-regexp ; 4
73 (regexp-quote "?="))))
80 (defun eword-decode-string (string &optional must-unfold)
81 "Decode MIME encoded-words in STRING.
83 STRING is unfolded before decoding.
85 If an encoded-word is broken or your emacs implementation can not
86 decode the charset included in it, it is not decoded.
88 If MUST-UNFOLD is non-nil, it unfolds and eliminates line-breaks even
89 if there are in decoded encoded-words (generated by bad manner MUA
90 such as a version of Net$cape)."
91 (setq string (std11-unfold-string string))
92 (let ((regexp (concat "[\n\t ]*\\(" eword-encoded-word-regexp "\\)"))
95 (while (setq match (string-match regexp string next))
96 (setq start (match-beginning 1)
99 (setq next (match-end 0))
100 (push (list (match-string 2 string) ;; charset
101 (match-string 3 string) ;; language
102 (match-string 4 string) ;; encoding
103 (match-string 5 string) ;; encoded-text
104 (match-string 1 string)) ;; encoded-word
106 (setq match (and (string-match regexp string next)
107 (= next (match-beginning 0)))))
108 (setq words (eword-decode-encoded-words (nreverse words) must-unfold)
109 string (concat (substring string 0 start)
111 (substring string next))
112 next (+ start (length words)))))
115 (defun eword-decode-structured-field-body (string
116 &optional start-column max-column
118 (let ((tokens (eword-lexical-analyze string start 'must-unfold))
122 (setq token (car tokens))
123 (setq result (concat result (eword-decode-token token)))
124 (setq tokens (cdr tokens)))
127 (defun eword-decode-and-unfold-structured-field-body (string
132 "Decode and unfold STRING as structured field body.
133 It decodes non us-ascii characters in FULL-NAME encoded as
134 encoded-words or invalid \"raw\" string. \"Raw\" non us-ascii
135 characters are regarded as variable `default-mime-charset'.
137 If an encoded-word is broken or your emacs implementation can not
138 decode the charset included in it, it is not decoded."
139 (let ((tokens (eword-lexical-analyze string start 'must-unfold))
142 (let* ((token (car tokens))
144 (setq tokens (cdr tokens))
146 (if (eq type 'spaces)
148 (concat result (eword-decode-token token))
152 (defun eword-decode-and-fold-structured-field-body (string
156 (if (and mime-field-decoding-max-size
157 (> (length string) mime-field-decoding-max-size))
160 (setq max-column fill-column))
161 (let ((c start-column)
162 (tokens (eword-lexical-analyze string start 'must-unfold))
165 (while (and (setq token (car tokens))
166 (setq tokens (cdr tokens)))
167 (let* ((type (car token)))
168 (if (eq type 'spaces)
169 (let* ((next-token (car tokens))
170 (next-str (eword-decode-token next-token))
171 (next-len (string-width next-str))
172 (next-c (+ c next-len 1)))
173 (if (< next-c max-column)
174 (setq result (concat result " " next-str)
176 (setq result (concat result "\n " next-str)
178 (setq tokens (cdr tokens))
180 (let* ((str (eword-decode-token token)))
181 (setq result (concat result str)
182 c (+ c (string-width str)))
185 (concat result (eword-decode-token token))
188 ;; unlimited patch by simm-emacs@fan.gr.jp
189 ;; Tue, 01 Feb 2000 13:43:09 +0900
190 (defun eword-decode-unstructured-field-body (string &optional start-column
193 (decode-mime-charset-string-unlimited
195 (or default-mime-charset-unlimited default-mime-charset))))
197 (defun eword-decode-and-unfold-unstructured-field-body (string
198 &optional start-column
201 (decode-mime-charset-string-unlimited
202 (std11-unfold-string string)
203 (or default-mime-charset-unlimited default-mime-charset))
206 (defun eword-decode-unfolded-unstructured-field-body (string
207 &optional start-column
210 (decode-mime-charset-string-unlimited
212 (or default-mime-charset-unlimited default-mime-charset))
219 (defun eword-decode-region (start end &optional unfolding must-unfold)
220 "Decode MIME encoded-words in region between START and END.
222 If UNFOLDING is not nil, it unfolds before decoding.
224 If MUST-UNFOLD is non-nil, it unfolds and eliminates line-breaks even
225 if there are in decoded encoded-words (generated by bad manner MUA
226 such as a version of Net$cape)."
230 (narrow-to-region start end)
232 (eword-decode-unfold))
233 (goto-char (point-min))
234 (let ((regexp (concat "[\n\t ]*\\(" eword-encoded-word-regexp "\\)"))
236 (while (setq match (re-search-forward regexp nil t))
237 (setq start (match-beginning 1)
240 (goto-char (setq end (match-end 0)))
241 (push (list (match-string 2) ;; charset
242 (match-string 3) ;; language
243 (match-string 4) ;; encoding
244 (match-string 5) ;; encoded-text
245 (match-string 1)) ;; encoded-word
247 (setq match (looking-at regexp)))
248 (delete-region start end)
250 (eword-decode-encoded-words (nreverse words) must-unfold)))))))
252 (defun eword-decode-unfold ()
253 (goto-char (point-min))
255 (while (re-search-forward std11-field-head-regexp nil t)
256 (setq beg (match-beginning 0)
257 end (std11-field-end))
258 (setq field (buffer-substring beg end))
259 (if (string-match eword-encoded-word-regexp field)
261 (narrow-to-region (goto-char beg) end)
262 (while (re-search-forward "\n\\([ \t]\\)" nil t)
263 (replace-match (match-string 1))
265 (goto-char (point-max))
270 ;;; @ for message header
273 (defvar mime-field-decoder-alist nil)
275 (defvar mime-field-decoder-cache nil)
277 (defvar mime-update-field-decoder-cache 'mime-update-field-decoder-cache
278 "*Field decoder cache update function.")
281 (defun mime-set-field-decoder (field &rest specs)
282 "Set decoder of FIELD.
283 SPECS must be like `MODE1 DECODER1 MODE2 DECODER2 ...'.
284 Each mode must be `nil', `plain', `wide', `summary' or `nov'.
285 If mode is `nil', corresponding decoder is set up for every modes."
287 (let ((mode (pop specs))
288 (function (pop specs)))
291 (let ((cell (assq mode mime-field-decoder-alist)))
293 (setcdr cell (put-alist field function (cdr cell)))
294 (setq mime-field-decoder-alist
295 (cons (cons mode (list (cons field function)))
296 mime-field-decoder-alist))
298 (apply (function mime-set-field-decoder) field specs)
300 (mime-set-field-decoder field
308 (defmacro mime-find-field-presentation-method (name)
309 "Return field-presentation-method from NAME.
310 NAME must be `plain', `wide', `summary' or `nov'."
312 `(or (assq 'summary mime-field-decoder-cache)
318 (symbolp (car (cdr name)))
319 (null (cdr (cdr name))))
320 `(or (assq ,name mime-field-decoder-cache)
324 `(or (assq (or ,name 'summary) mime-field-decoder-cache)
325 (cons (or ,name 'summary) nil))
328 (defun mime-find-field-decoder-internal (field &optional mode)
329 "Return function to decode field-body of FIELD in MODE.
330 Optional argument MODE must be object of field-presentation-method."
331 (cdr (or (assq field (cdr mode))
333 (funcall mime-update-field-decoder-cache
336 (cdr (assq (car mode) mime-field-decoder-cache)))
340 (defun mime-find-field-decoder (field &optional mode)
341 "Return function to decode field-body of FIELD in MODE.
342 Optional argument MODE must be object or name of
343 field-presentation-method. Name of field-presentation-method must be
344 `plain', `wide', `summary' or `nov'.
345 Default value of MODE is `summary'."
347 (let ((p (cdr (mime-find-field-presentation-method mode))))
348 (if (and p (setq p (assq field p)))
350 (cdr (funcall mime-update-field-decoder-cache
351 field (or mode 'summary)))))
352 (inline (mime-find-field-decoder-internal field mode))
356 (defun mime-update-field-decoder-cache (field mode &optional function)
357 "Update field decoder cache `mime-field-decoder-cache'."
358 (cond ((eq function 'identity)
363 (cdr (assq (or mode 'summary) mime-field-decoder-alist))))
364 (setq function (cdr (or (assq field decoder-alist)
365 (assq t decoder-alist)))))
367 (let ((cell (assq mode mime-field-decoder-cache))
370 (if (setq ret (assq field (cdr cell)))
371 (setcdr ret function)
372 (setcdr cell (cons (setq ret (cons field function)) (cdr cell))))
373 (setq mime-field-decoder-cache
374 (cons (cons mode (list (setq ret (cons field function))))
375 mime-field-decoder-cache)))
379 (mime-set-field-decoder 'Archive nil nil)
380 (mime-set-field-decoder 'Content-Md5 nil nil)
381 (mime-set-field-decoder 'Control nil nil)
382 (mime-set-field-decoder 'Date nil nil)
383 (mime-set-field-decoder 'Distribution nil nil)
384 (mime-set-field-decoder 'Followup-Host nil nil)
385 (mime-set-field-decoder 'Followup-To nil nil)
386 (mime-set-field-decoder 'Lines nil nil)
387 (mime-set-field-decoder 'Message-Id nil nil)
388 (mime-set-field-decoder 'Newsgroups nil nil)
389 (mime-set-field-decoder 'Nntp-Posting-Host nil nil)
390 (mime-set-field-decoder 'Path nil nil)
391 (mime-set-field-decoder 'Posted-And-Mailed nil nil)
392 (mime-set-field-decoder 'Received nil nil)
393 (mime-set-field-decoder 'Status nil nil)
394 (mime-set-field-decoder 'X-Face nil nil)
395 (mime-set-field-decoder 'X-Face-Version nil nil)
396 (mime-set-field-decoder 'X-Info nil nil)
397 (mime-set-field-decoder 'X-Pgp-Key-Info nil nil)
398 (mime-set-field-decoder 'X-Pgp-Sig nil nil)
399 (mime-set-field-decoder 'X-Pgp-Sig-Version nil nil)
400 (mime-set-field-decoder 'Xref nil nil)
404 '(Reply-To Resent-Reply-To From Resent-From Sender Resent-Sender
405 To Resent-To Cc Resent-Cc Bcc Resent-Bcc Dcc
407 Mime-Version Content-Type Content-Transfer-Encoding
408 Content-Disposition User-Agent))
411 (setq field (pop fields))
412 (mime-set-field-decoder
414 'plain #'eword-decode-structured-field-body
415 'wide #'eword-decode-and-fold-structured-field-body
416 'summary #'eword-decode-and-unfold-structured-field-body
417 'nov #'eword-decode-and-unfold-structured-field-body)
420 ;; unstructured fields (default)
421 (mime-set-field-decoder
423 'plain #'eword-decode-unstructured-field-body
424 'wide #'eword-decode-unstructured-field-body
425 'summary #'eword-decode-and-unfold-unstructured-field-body
426 'nov #'eword-decode-unfolded-unstructured-field-body)
429 (defun mime-decode-field-body (field-body field-name
430 &optional mode max-column)
431 "Decode FIELD-BODY as FIELD-NAME in MODE, and return the result.
432 Optional argument MODE must be `plain', `wide', `summary' or `nov'.
433 Default mode is `summary'.
435 If MODE is `wide' and MAX-COLUMN is non-nil, the result is folded with
438 Non MIME encoded-word part in FILED-BODY is decoded with
439 `default-mime-charset'."
440 (let (field-name-symbol len decoder)
441 (if (symbolp field-name)
442 (setq field-name-symbol field-name
443 len (1+ (string-width (symbol-name field-name))))
444 (setq field-name-symbol (intern (capitalize field-name))
445 len (1+ (string-width field-name))))
446 (setq decoder (mime-find-field-decoder field-name-symbol mode))
448 (funcall decoder field-body len max-column)
450 (if (eq mode 'summary)
451 (std11-unfold-string field-body)
456 (defun mime-decode-header-in-region (start end
457 &optional code-conversion)
458 "Decode MIME encoded-words in region between START and END.
459 If CODE-CONVERSION is nil, it decodes only encoded-words. If it is
460 mime-charset, it decodes non-ASCII bit patterns as the mime-charset.
461 Otherwise it decodes non-ASCII bit patterns as the
462 default-mime-charset."
466 (narrow-to-region start end)
467 (let ((default-charset
469 (if (mime-charset-to-coding-system code-conversion)
471 default-mime-charset))))
473 (let ((mode-obj (mime-find-field-presentation-method 'wide))
474 beg p end field-name len field-decoder)
475 (goto-char (point-min))
476 (while (re-search-forward std11-field-head-regexp nil t)
477 (setq beg (match-beginning 0)
479 field-name (buffer-substring beg (1- p))
480 len (string-width field-name)
481 field-name (intern (capitalize field-name))
482 field-decoder (inline
483 (mime-find-field-decoder-internal
484 field-name mode-obj)))
486 (setq end (std11-field-end))
487 (let ((body (buffer-substring p end))
488 (default-mime-charset default-charset))
489 (delete-region p end)
490 (insert (funcall field-decoder body (1+ len)))
493 (eword-decode-region (point-min) (point-max) t)
497 (defun mime-decode-header-in-buffer (&optional code-conversion separator)
498 "Decode MIME encoded-words in header fields.
499 If CODE-CONVERSION is nil, it decodes only encoded-words. If it is
500 mime-charset, it decodes non-ASCII bit patterns as the mime-charset.
501 Otherwise it decodes non-ASCII bit patterns as the
502 default-mime-charset.
503 If SEPARATOR is not nil, it is used as header separator."
505 (mime-decode-header-in-region
508 (goto-char (point-min))
509 (if (re-search-forward
510 (concat "^\\(" (regexp-quote (or separator "")) "\\)?$")
517 (defalias 'eword-decode-header 'mime-decode-header-in-buffer)
518 (make-obsolete 'eword-decode-header 'mime-decode-header-in-buffer)
521 ;;; @ encoded-words decoder
524 (defvar eword-decode-allow-incomplete-encoded-text t
525 "*Non-nil means allow incomplete encoded-text in successive encoded-words.
526 Dividing of encoded-text in the place other than character boundaries
527 violates RFC2047 section 5, while we have a capability to decode it.
528 If it is non-nil, the decoder will decode B- or Q-encoding in each
529 encoded-word, concatenate them, and decode it by charset. Otherwise,
530 the decoder will fully decode each encoded-word before concatenating
533 (defun eword-decode-encoded-words (words must-unfold)
534 "Decode successive encoded-words in WORDS and return a decoded string.
535 Each element of WORDS looks like (CHARSET LANGUAGE ENCODING ENCODED-TEXT
538 If MUST-UNFOLD is non-nil, it unfolds and eliminates line-breaks even
539 if there are in decoded encoded-words (generated by bad manner MUA
540 such as a version of Net$cape)."
541 (let (word language charset encoding text rest)
543 (setq word (pop words)
544 language (nth 1 word))
545 (if (and (or (mime-charset-to-coding-system (setq charset (car word)))
547 (message "Unknown charset: %s" charset)
549 (cond ((member (setq encoding (nth 2 word)) '("B" "Q"))
551 ((member encoding '("b" "q"))
552 (setq encoding (upcase encoding)))
554 (message "Invalid encoding: %s" encoding)
558 (encoded-text-decode-string (nth 3 word) encoding))
560 (message "%s" (error-message-string err))
562 (if (and eword-decode-allow-incomplete-encoded-text
565 (string-equal (downcase charset) (downcase (caaar rest)))
566 (equal language (cdaar rest)))
567 ;; Concatenate text of which the charset is the same.
568 (setcdr (car rest) (concat (cdar rest) text))
569 (push (cons (cons charset language) text) rest))
570 ;; Don't decode encoded-word.
571 (push (cons (cons nil language) (nth 4 word)) rest)))
573 (setq word (or (and (setq charset (caaar rest))
575 (decode-mime-charset-string (cdar rest) charset)
577 (message "%s" (error-message-string err))
579 (concat (when (cdr rest) " ")
582 (not (eq (string-to-char words) ? )))
585 (setq word (mapconcat (lambda (chr)
586 (cond ((eq chr ?\n) "")
589 (t (char-to-string chr))))
590 (std11-unfold-string word)
592 (when (setq language (cdaar rest))
593 (put-text-property 0 (length word) 'mime-language language word))
594 (setq words (concat word words)
598 ;;; @ lexical analyze
601 (defvar eword-lexical-analyze-cache nil)
602 (defvar eword-lexical-analyze-cache-max 299
603 "*Max position of eword-lexical-analyze-cache.
604 It is max size of eword-lexical-analyze-cache - 1.")
606 (defvar mime-header-lexical-analyzer
607 '(eword-analyze-quoted-string
608 eword-analyze-domain-literal
609 eword-analyze-comment
611 eword-analyze-special
612 eword-analyze-encoded-word
614 "*List of functions to return result of lexical analyze.
615 Each function must have three arguments: STRING, START and MUST-UNFOLD.
616 STRING is the target string to be analyzed.
617 START is start position of STRING to analyze.
618 If MUST-UNFOLD is not nil, each function must unfold and eliminate
619 bare-CR and bare-LF from the result even if they are included in
620 content of the encoded-word.
621 Each function must return nil if it can not analyze STRING as its
624 Previous function is preferred to next function. If a function
625 returns nil, next function is used. Otherwise the return value will
628 (defun eword-analyze-quoted-string (string start &optional must-unfold)
629 (let ((p (std11-check-enclosure string ?\" ?\" nil start))
632 (setq ret (decode-mime-charset-string
633 (std11-strip-quoted-pair
634 (substring string (1+ start) (1- p)))
635 default-mime-charset))
636 (if mime-header-accept-quoted-encoded-words
637 (setq ret (eword-decode-string ret)))
638 (cons (cons 'quoted-string ret)
641 (defun eword-analyze-domain-literal (string start &optional must-unfold)
642 (std11-analyze-domain-literal string start))
644 (defun eword-analyze-comment (string from &optional must-unfold)
645 (let ((len (length string))
650 (eq (aref string i) ?\())
655 (setq chr (aref string i))
661 (setq last-str (concat last-str
662 (substring string from (1- i))
663 (char-to-string (aref string i)))
668 (setq ret (concat last-str
669 (substring string from i)))
677 (decode-mime-charset-string
678 ret default-mime-charset)
685 (if (setq ret (eword-analyze-comment string i must-unfold))
688 (substring string from i))
690 (if (string= last-str "")
691 (cons (car ret) dest)
694 (decode-mime-charset-string
695 last-str default-mime-charset)
709 (defun eword-analyze-spaces (string start &optional must-unfold)
710 (std11-analyze-spaces string start))
712 (defun eword-analyze-special (string start &optional must-unfold)
713 (std11-analyze-special string start))
715 (defun eword-analyze-encoded-word (string start &optional must-unfold)
716 (let* ((regexp (concat "[\n\t ]*\\(" eword-encoded-word-regexp "\\)"))
717 (match (and (string-match regexp string start)
718 (= start (match-beginning 0))))
721 (setq next (match-end 0))
722 (push (list (match-string 2 string) ;; charset
723 (match-string 3 string) ;; language
724 (match-string 4 string) ;; encoding
725 (match-string 5 string) ;; encoded-text
726 (match-string 1 string)) ;; encoded-word
728 (setq match (and (string-match regexp string next)
729 (= next (match-beginning 0)))))
731 (cons (cons 'atom (eword-decode-encoded-words (nreverse words)
735 (defun eword-analyze-atom (string start &optional must-unfold)
736 (if (and (string-match std11-atom-regexp string start)
737 (= (match-beginning 0) start))
738 (let ((end (match-end 0)))
739 (cons (cons 'atom (decode-mime-charset-string
740 (substring string start end)
741 default-mime-charset))
742 ;;(substring string end)
746 (defun eword-lexical-analyze-internal (string start must-unfold)
747 (let ((len (length string))
751 (let ((rest mime-header-lexical-analyzer)
753 ;; unlimited patch by simm-emacs@fan.gr.jp,
754 ;; Mon, 10 Jan 2000 12:52:39 +0900
755 (while (and (setq func (car rest))
756 (or (and mime-decode-unlimited
757 (eq func 'eword-analyze-quoted-string))
759 (setq r (funcall func string start must-unfold)))))
760 (setq rest (cdr rest)))
762 (cons (cons 'error (substring string start)) (1+ len)))
764 (setq dest (cons (car ret) dest)
770 (defun eword-lexical-analyze (string &optional start must-unfold)
771 "Return lexical analyzed list corresponding STRING.
772 It is like std11-lexical-analyze, but it decodes non us-ascii
773 characters encoded as encoded-words or invalid \"raw\" format.
774 \"Raw\" non us-ascii characters are regarded as variable
775 `default-mime-charset'."
776 (let ((key (substring string (or start 0)))
778 (set-text-properties 0 (length key) nil key)
779 (if (setq ret (assoc key eword-lexical-analyze-cache))
781 (setq ret (eword-lexical-analyze-internal key 0 must-unfold))
782 (setq eword-lexical-analyze-cache
784 eword-lexical-analyze-cache))
785 (if (cdr (setq cell (nthcdr eword-lexical-analyze-cache-max
786 eword-lexical-analyze-cache)))
790 (defun eword-decode-token (token)
791 (let ((type (car token))
793 (cond ((eq type 'quoted-string)
794 (std11-wrap-as-quoted-string value))
798 (setq dest (concat dest
799 (if (stringp (car value))
800 ;; unlimited patch by simm-emacs@fan.gr.jp
801 ;; Mon, 10 Jan 2000 12:53:46 +0900
802 (if mime-decode-unlimited
804 (std11-wrap-as-quoted-pairs
805 (car value) '(?( ?))))
806 (std11-wrap-as-quoted-pairs
807 (car value) '(?( ?))))
808 (eword-decode-token (car value))
812 (concat "(" dest ")")
816 (defun eword-extract-address-components (string &optional start)
817 "Extract full name and canonical address from STRING.
818 Returns a list of the form (FULL-NAME CANONICAL-ADDRESS).
819 If no name can be extracted, FULL-NAME will be nil.
820 It decodes non us-ascii characters in FULL-NAME encoded as
821 encoded-words or invalid \"raw\" string. \"Raw\" non us-ascii
822 characters are regarded as variable `default-mime-charset'."
823 (let* ((structure (car (std11-parse-address
824 (eword-lexical-analyze
825 (std11-unfold-string string) start
827 (phrase (std11-full-name-string structure))
828 (address (std11-address-string structure))
830 (list phrase address)
837 (provide 'eword-decode)
839 ;;; eword-decode.el ends here