1 ;;; rfc2047.el --- functions for encoding and decoding rfc2047 messages
2 ;; Copyright (C) 1998, 1999, 2000, 2002, 2003 Free Software Foundation, Inc.
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; MORIOKA Tomohiko <morioka@jaist.ac.jp>
6 ;; This file is part of GNU Emacs.
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING. If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
25 ;; RFC 2047 is "MIME (Multipurpose Internet Mail Extensions) Part
26 ;; Three: Message Header Extensions for Non-ASCII Text".
32 (defvar message-posting-charset)
33 (unless (fboundp 'with-syntax-table) ; not in Emacs 20
34 (defmacro with-syntax-table (table &rest body)
35 "Evaluate BODY with syntax table of current buffer set to TABLE.
36 The syntax table of the current buffer is saved, BODY is evaluated, and the
37 saved table is restored, even in case of an abnormal exit.
38 Value is what BODY returns."
39 (let ((old-table (make-symbol "table"))
40 (old-buffer (make-symbol "buffer")))
41 `(let ((,old-table (syntax-table))
42 (,old-buffer (current-buffer)))
45 (set-syntax-table ,table)
48 (set-buffer ,old-buffer)
49 (set-syntax-table ,old-table))))))))
53 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
56 (autoload 'mm-body-7-or-8 "mm-bodies")
59 ;; Avoid gnus-util for mm- code.
60 (defalias 'rfc2047-point-at-bol
61 (if (fboundp 'point-at-bol)
63 'line-beginning-position))
65 (defalias 'rfc2047-point-at-eol
66 (if (fboundp 'point-at-eol)
70 (defvar rfc2047-header-encoding-alist
71 '(("Newsgroups" . nil)
74 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\)" .
77 "*Header/encoding method alist.
78 The list is traversed sequentially. The keys can either be
83 1) nil, in which case no encoding is done;
84 2) `mime', in which case the header will be encoded according to RFC2047;
85 3) `address-mime', like `mime', but takes account of the rules for address
86 fields (where quoted strings and comments must be treated separately);
87 4) a charset, in which case it will be encoded as that charset;
88 5) `default', in which case the field will be encoded as the rest
91 (defvar rfc2047-charset-encoding-alist
113 (iso-2022-int-1 . B))
114 "Alist of MIME charsets to RFC2047 encodings.
115 Valid encodings are nil, `Q' and `B'. These indicate binary (no) encoding,
116 quoted-printable and base64 respectively.")
118 (defvar rfc2047-encoding-function-alist
119 '((Q . rfc2047-q-encode-region)
120 (B . rfc2047-b-encode-region)
122 "Alist of RFC2047 encodings to encoding functions.")
125 ;;; Functions for encoding RFC2047 messages
128 (defun rfc2047-narrow-to-field ()
129 "Narrow the buffer to the header on the current line."
135 (if (re-search-forward "^[^ \n\t]" nil t)
140 (goto-char (point-min)))
142 (defun rfc2047-field-value ()
143 "Return the value of the field at point."
146 (rfc2047-narrow-to-field)
147 (re-search-forward ":[ \t\n]*" nil t)
148 (buffer-substring (point) (point-max)))))
150 (defvar rfc2047-encoding-type 'address-mime
151 "The type of encoding done by `rfc2047-encode-region'.
152 This should be dynamically bound around calls to
153 `rfc2047-encode-region' to either `mime' or `address-mime'. See
154 `rfc2047-header-encoding-alist', for definitions.")
156 (defun rfc2047-encode-message-header ()
157 "Encode the message header according to `rfc2047-header-encoding-alist'.
158 Should be called narrowed to the head of the message."
161 (goto-char (point-min))
162 (let (alist elem method)
165 (rfc2047-narrow-to-field)
166 (if (not (rfc2047-encodable-p))
168 (if (and (eq (mm-body-7-or-8) '8bit)
171 (car message-posting-charset)))
172 ;; 8 bit must be decoded.
173 (mm-encode-coding-region
174 (point-min) (point-max)
175 (mm-charset-to-coding-system
176 (car message-posting-charset))))
177 ;; No encoding necessary, but folding is nice
180 (goto-char (point-min))
181 (skip-chars-forward "^:")
182 (when (looking-at ": ")
186 ;; We found something that may perhaps be encoded.
188 alist rfc2047-header-encoding-alist)
189 (while (setq elem (pop alist))
190 (when (or (and (stringp (car elem))
191 (looking-at (car elem)))
195 (goto-char (point-min))
196 (re-search-forward "^[^:]+: *" nil t)
198 ((eq method 'address-mime)
199 (rfc2047-encode-region (point) (point-max)))
201 (let ((rfc2047-encoding-type 'mime))
202 (rfc2047-encode-region (point) (point-max))))
203 ((eq method 'default)
204 (if (and (featurep 'mule)
205 (if (boundp 'default-enable-multibyte-characters)
206 default-enable-multibyte-characters)
208 (mm-encode-coding-region (point) (point-max)
209 mail-parse-charset)))
210 ;; We get this when CC'ing messsages to newsgroups with
211 ;; 8-bit names. The group name mail copy just got
212 ;; unconditionally encoded. Previously, it would ask
213 ;; whether to encode, which was quite confusing for the
214 ;; user. If the new behaviour is wrong, tell me. I have
215 ;; left the old code commented out below.
216 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
217 ;; Modified by Dave Love, with the commented-out code changed
218 ;; in accordance with changes elsewhere.
220 (rfc2047-encode-region (point) (point-max)))
222 ;;; (if (or (message-options-get
223 ;;; 'rfc2047-encode-message-header-encode-any)
224 ;;; (message-options-set
225 ;;; 'rfc2047-encode-message-header-encode-any
227 ;;; "Some texts are not encoded. Encode anyway?")))
228 ;;; (rfc2047-encode-region (point-min) (point-max))
229 ;;; (error "Cannot send unencoded text")))
230 ((mm-coding-system-p method)
231 (if (and (featurep 'mule)
232 (if (boundp 'default-enable-multibyte-characters)
233 default-enable-multibyte-characters))
234 (mm-encode-coding-region (point) (point-max) method)))
237 (goto-char (point-max)))))))
239 ;; Fixme: This, and the require below may not be the Right Thing, but
240 ;; should be safe just before release. -- fx 2001-02-08
241 (eval-when-compile (defvar message-posting-charset))
243 (defun rfc2047-encodable-p ()
244 "Return non-nil if any characters in current buffer need encoding in headers.
245 The buffer may be narrowed."
246 (require 'message) ; for message-posting-charset
248 (mm-find-mime-charset-region (point-min) (point-max))))
250 (not (equal charsets (list (car message-posting-charset)))))))
252 ;; Use this syntax table when parsing into regions that may need
253 ;; encoding. Double quotes are string delimiters, backslash is
254 ;; character quoting, and all other RFC 2822 special characters are
255 ;; treated as punctuation so we can use forward-sexp/forward-word to
256 ;; skip to the end of regions appropriately. Nb. ietf-drums does
257 ;; things differently.
258 (defconst rfc2047-syntax-table
259 ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
260 (let ((table (make-syntax-table)))
261 ;; The following is done to work for setting all elements of the table
262 ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
263 ;; Play safe and don't assume the form of the word syntax entry --
265 (if (fboundp 'set-char-table-range) ; Emacs
266 (funcall (intern "set-char-table-range")
267 table t (aref (standard-syntax-table) ?a))
268 (if (fboundp 'put-char-table)
269 (if (fboundp 'get-char-table) ; warning avoidance
270 (put-char-table t (get-char-table ?a (standard-syntax-table))
272 (modify-syntax-entry ?\\ "\\" table)
273 (modify-syntax-entry ?\" "\"" table)
274 (modify-syntax-entry ?\( "." table)
275 (modify-syntax-entry ?\) "." table)
276 (modify-syntax-entry ?\< "." table)
277 (modify-syntax-entry ?\> "." table)
278 (modify-syntax-entry ?\[ "." table)
279 (modify-syntax-entry ?\] "." table)
280 (modify-syntax-entry ?: "." table)
281 (modify-syntax-entry ?\; "." table)
282 (modify-syntax-entry ?, "." table)
283 (modify-syntax-entry ?@ "." table)
286 (defun rfc2047-encode-region (b e)
287 "Encode words in region B to E that need encoding.
288 By default, the region is treated as containing RFC2822 addresses.
289 Dynamically bind `rfc2047-encoding-type' to change that."
291 (narrow-to-region b e)
292 (if (eq 'mime rfc2047-encoding-type)
293 ;; Simple case. Treat as single word after any initial ASCII
294 ;; part and before any tailing ASCII part. The leading ASCII
295 ;; is relevant for instance in Subject headers with `Re:' for
296 ;; interoperability with non-MIME clients, and we might as
297 ;; well avoid the tail too.
299 (goto-char (point-min))
300 ;; Does it need encoding?
301 (skip-chars-forward "\000-\177")
303 (skip-chars-backward "^ \n") ; beginning of space-delimited word
304 (rfc2047-encode (point) (progn
306 (skip-chars-backward "\000-\177")
307 (skip-chars-forward "^ \n")
308 ;; end of space-delimited word
310 ;; `address-mime' case -- take care of quoted words, comments.
311 (with-syntax-table rfc2047-syntax-table
312 (let ((start) ; start of current token
313 end ; end of current token
314 ;; Whether there's an encoded word before the current
315 ;; token, either immediately or separated by space.
317 (goto-char (point-min))
318 (condition-case nil ; in case of unbalanced quotes
319 ;; Look for rfc2822-style: sequences of atoms, quoted
320 ;; strings, specials, whitespace. (Specials mustn't be
325 (unless (= 0 (skip-chars-forward " \t\n"))
326 (setq start (point)))
328 ((not (char-after))) ; eob
330 ((eq ?\" (char-syntax (char-after)))
334 ;; Does it need encoding?
336 (skip-chars-forward "\000-\177" end)
338 (setq last-encoded nil)
339 ;; It needs encoding. Strip the quotes first,
340 ;; since encoded words can't occur in quotes.
342 (delete-backward-char 1)
346 ;; There was a preceding quoted word. We need
347 ;; to include any separating whitespace in this
348 ;; word to avoid it getting lost.
349 (skip-chars-backward " \t")
350 ;; A space is needed between the encoded words.
354 ;; Adjust the end position for the deleted quotes.
355 (rfc2047-encode start (- end 2))
356 (setq last-encoded t))) ; record that it was encoded
357 ((eq ?. (char-syntax (char-after)))
358 ;; Skip other delimiters, but record that they've
359 ;; potentially separated quoted words.
361 (setq last-encoded nil))
362 (t ; normal token/whitespace sequence
365 (skip-chars-backward " \t")
367 ;; Deal with encoding and leading space as for
370 (skip-chars-forward "\000-\177" end)
372 (setq last-encoded nil)
375 (skip-chars-backward " \t")
379 (rfc2047-encode start end)
380 (setq last-encoded t)))))
381 (error (error "Invalid data for rfc2047 encoding: %s"
382 (buffer-substring b e)))))))
383 (rfc2047-fold-region b (point))))
385 (defun rfc2047-encode-string (string)
386 "Encode words in STRING.
387 By default, the string is treated as containing addresses (see
388 `rfc2047-encoding-type')."
391 (rfc2047-encode-region (point-min) (point-max))
394 (defun rfc2047-encode (b e)
395 "Encode the word(s) in the region B to E.
396 By default, the region is treated as containing addresses (see
397 `rfc2047-encoding-type')."
398 (let* ((mime-charset (mm-find-mime-charset-region b e))
399 (cs (if (> (length mime-charset) 1)
400 ;; Fixme: Instead of this, try to break region into
401 ;; parts that can be encoded separately.
402 (error "Can't rfc2047-encode `%s'"
403 (buffer-substring b e))
404 (setq mime-charset (car mime-charset))
405 (mm-charset-to-coding-system mime-charset)))
406 ;; Fixme: Better, calculate the number of non-ASCII
407 ;; characters, at least for 8-bit charsets.
408 (encoding (if (assq mime-charset
409 rfc2047-charset-encoding-alist)
410 (cdr (assq mime-charset
411 rfc2047-charset-encoding-alist))
414 "=?" (downcase (symbol-name mime-charset)) "?"
415 (downcase (symbol-name encoding)) "?"))
419 (narrow-to-region b e)
420 (when (eq encoding 'B)
421 ;; break into lines before encoding
422 (goto-char (point-min))
424 (goto-char (min (point-max) (+ 15 (point))))
427 (if (and (mm-multibyte-p)
428 (mm-coding-system-p cs))
429 (mm-encode-coding-region (point-min) (point-max) cs))
430 (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
431 (point-min) (point-max))
432 (goto-char (point-min))
440 (forward-line 1))))))
442 (defun rfc2047-fold-field ()
443 "Fold the current header field."
446 (rfc2047-narrow-to-field)
447 (rfc2047-fold-region (point-min) (point-max)))))
449 (defun rfc2047-fold-region (b e)
450 "Fold long lines in region B to E."
452 (narrow-to-region b e)
453 (goto-char (point-min))
457 (bol (save-restriction
459 (rfc2047-point-at-bol))))
461 (when (and (or break qword-break)
462 (> (- (point) bol) 76))
463 (goto-char (or break qword-break))
466 (if (looking-at "[ \t]")
469 (setq bol (1- (point)))
470 ;; Don't break before the first non-LWSP characters.
471 (skip-chars-forward " \t")
475 ((eq (char-after) ?\n)
480 (skip-chars-forward " \t")
481 (unless (or (eobp) (eq (char-after) ?\n))
483 ((eq (char-after) ?\r)
485 ((memq (char-after) '(? ?\t))
486 (skip-chars-forward " \t")
488 ;; Don't break just after the header name.
490 (setq break (1- (point)))))
492 (if (not (looking-at "=\\?[^=]"))
493 (if (eq (char-after) ?=)
495 (skip-chars-forward "^ \t\n\r="))
496 (setq qword-break (point))
497 (skip-chars-forward "^ \t\n\r")))
499 (skip-chars-forward "^ \t\n\r"))))
500 (when (and (or break qword-break)
501 (> (- (point) bol) 76))
502 (goto-char (or break qword-break))
505 (if (looking-at "[ \t]")
508 (setq bol (1- (point)))
509 ;; Don't break before the first non-LWSP characters.
510 (skip-chars-forward " \t")
512 (forward-char 1))))))
514 (defun rfc2047-unfold-field ()
515 "Fold the current line."
518 (rfc2047-narrow-to-field)
519 (rfc2047-unfold-region (point-min) (point-max)))))
521 (defun rfc2047-unfold-region (b e)
522 "Unfold lines in region B to E."
524 (narrow-to-region b e)
525 (goto-char (point-min))
526 (let ((bol (save-restriction
528 (rfc2047-point-at-bol)))
529 (eol (rfc2047-point-at-eol)))
532 (if (and (looking-at "[ \t]")
533 (< (- (rfc2047-point-at-eol) bol) 76))
534 (delete-region eol (progn
536 (skip-chars-forward "\r\n")
538 (setq bol (rfc2047-point-at-bol)))
539 (setq eol (rfc2047-point-at-eol))
542 (defun rfc2047-b-encode-region (b e)
543 "Base64-encode the header contained in region B to E."
545 (narrow-to-region (goto-char b) e)
547 (base64-encode-region (point) (progn (end-of-line) (point)) t)
548 (if (and (bolp) (eolp))
549 (delete-backward-char 1))
552 (defun rfc2047-q-encode-region (b e)
553 "Quoted-printable-encode the header in region B to E."
556 (narrow-to-region (goto-char b) e)
557 (let ((bol (save-restriction
559 (rfc2047-point-at-bol))))
560 (quoted-printable-encode-region
562 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
563 ;; Avoid using 8bit characters.
564 ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
565 "\010\012\014\040-\074\076\100-\136\140-\177")
566 (subst-char-in-region (point-min) (point-max) ? ?_)
567 ;; The size of QP encapsulation is about 20, so set limit to
569 (unless (< (- (point-max) (point-min)) 56)
570 ;; Don't break if it could fit in one line.
571 ;; Let rfc2047-encode-region break it later.
572 (goto-char (1+ (point-min)))
573 (while (and (not (bobp)) (not (eobp)))
574 (goto-char (min (point-max) (+ 56 bol)))
575 (search-backward "=" (- (point) 2) t)
576 (unless (or (bobp) (eobp))
578 (setq bol (point)))))))))
581 ;;; Functions for decoding RFC2047 messages
585 (defconst rfc2047-encoded-word-regexp
586 "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\
587 \\?\\([!->@-~ +]*\\)\\?="))
589 ;; Fixme: This should decode in place, not cons intermediate strings.
590 ;; Also check whether it needs to worry about delimiting fields like
593 ;; In fact it's reported that (invalid) encoding of mailboxes in
594 ;; addr-specs is in use, so delimiting fields might help. Probably
595 ;; not decoding a word which isn't properly delimited is good enough
596 ;; and worthwhile (is it more correct or not?), e.g. something like
597 ;; `=?iso-8859-1?q?foo?=@'.
599 (defun rfc2047-decode-region (start end)
600 "Decode MIME-encoded words in region between START and END."
602 (let ((case-fold-search t)
606 (narrow-to-region start end)
607 (goto-char (point-min))
608 ;; Remove whitespace between encoded words.
609 (while (re-search-forward
611 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
613 "\\(" rfc2047-encoded-word-regexp "\\)"))
615 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
616 ;; Decode the encoded words.
617 (setq b (goto-char (point-min)))
618 (while (re-search-forward rfc2047-encoded-word-regexp nil t)
619 (setq e (match-beginning 0))
620 (insert (rfc2047-parse-and-decode
623 (delete-region (match-beginning 0) (match-end 0)))))
624 ;; Remove newlines between decoded words, though such things
625 ;; essentially must not be there.
627 (narrow-to-region e (point))
629 (while (re-search-forward "[\n\r]+" nil t)
631 (goto-char (point-max)))
632 (when (and (mm-multibyte-p)
634 (not (eq mail-parse-charset 'us-ascii))
635 (not (eq mail-parse-charset 'gnus-decoded)))
636 (mm-decode-coding-region b e mail-parse-charset))
638 (when (and (mm-multibyte-p)
640 (not (eq mail-parse-charset 'us-ascii))
641 (not (eq mail-parse-charset 'gnus-decoded)))
642 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
644 (defun rfc2047-decode-string (string)
645 "Decode the quoted-printable-encoded STRING and return the results."
646 (let ((m (mm-multibyte-p)))
647 (if (string-match "=\\?" string)
649 ;; Fixme: This logic is wrong, but seems to be required by
650 ;; Gnus summary buffer generation. The value of `m' depends
651 ;; on the current buffer, not global multibyteness or that
652 ;; of the string. Also the string returned should always be
653 ;; multibyte in a multibyte session, i.e. the buffer should
654 ;; be multibyte before `buffer-string' is called.
656 (mm-enable-multibyte))
659 (rfc2047-decode-region (point-min) (point-max)))
661 ;; Fixme: As above, `m' here is inappropriate.
664 (not (eq mail-parse-charset 'us-ascii))
665 (not (eq mail-parse-charset 'gnus-decoded)))
666 (mm-decode-coding-string string mail-parse-charset)
667 (mm-string-as-multibyte string)))))
669 (defun rfc2047-parse-and-decode (word)
670 "Decode WORD and return it if it is an encoded word.
671 Return WORD if it is not not an encoded word or if the charset isn't
673 (if (not (string-match rfc2047-encoded-word-regexp word))
678 (match-string 1 word)
679 (upcase (match-string 2 word))
680 (match-string 3 word))
682 word))) ; un-decodable
684 (defun rfc2047-pad-base64 (string)
685 "Pad STRING to quartets."
686 ;; Be more liberal to accept buggy base64 strings. If
687 ;; base64-decode-string accepts buggy strings, this function could
688 ;; be aliased to identity.
689 (case (mod (length string) 4)
691 (1 string) ;; Error, don't pad it.
692 (2 (concat string "=="))
693 (3 (concat string "="))))
695 (defun rfc2047-decode (charset encoding string)
696 "Decode STRING from the given MIME CHARSET in the given ENCODING.
697 Valid ENCODINGs are \"B\" and \"Q\".
698 If your Emacs implementation can't decode CHARSET, return nil."
699 (if (stringp charset)
700 (setq charset (intern (downcase charset))))
701 (if (or (not charset)
702 (eq 'gnus-all mail-parse-ignored-charsets)
703 (memq 'gnus-all mail-parse-ignored-charsets)
704 (memq charset mail-parse-ignored-charsets))
705 (setq charset mail-parse-charset))
706 (let ((cs (mm-charset-to-coding-system charset)))
707 (if (and (not cs) charset
708 (listp mail-parse-ignored-charsets)
709 (memq 'gnus-unknown mail-parse-ignored-charsets))
710 (setq cs (mm-charset-to-coding-system mail-parse-charset)))
712 (when (and (eq cs 'ascii)
714 (setq cs mail-parse-charset))
715 (mm-decode-coding-string
717 ((equal "B" encoding)
718 (base64-decode-string
719 (rfc2047-pad-base64 string)))
720 ((equal "Q" encoding)
721 (quoted-printable-decode-string
722 (mm-replace-chars-in-string string ?_ ? )))
723 (t (error "Invalid encoding: %s" encoding)))
728 ;;; rfc2047.el ends here