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.")
124 (defvar rfc2047-q-encoding-alist
125 '(("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\):"
127 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
128 ;; Avoid using 8bit characters.
129 ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
130 ("." . "\010\012\014\040-\074\076\100-\136\140-\177"))
131 "Alist of header regexps and valid Q characters.")
134 ;;; Functions for encoding RFC2047 messages
137 (defun rfc2047-narrow-to-field ()
138 "Narrow the buffer to the header on the current line."
144 (if (re-search-forward "^[^ \n\t]" nil t)
149 (goto-char (point-min)))
151 (defun rfc2047-field-value ()
152 "Return the value of the field at point."
155 (rfc2047-narrow-to-field)
156 (re-search-forward ":[ \t\n]*" nil t)
157 (buffer-substring (point) (point-max)))))
159 (defvar rfc2047-encoding-type 'address-mime
160 "The type of encoding done by `rfc2047-encode-region'.
161 This should be dynamically bound around calls to
162 `rfc2047-encode-region' to either `mime' or `address-mime'. See
163 `rfc2047-header-encoding-alist', for definitions.")
165 (defun rfc2047-encode-message-header ()
166 "Encode the message header according to `rfc2047-header-encoding-alist'.
167 Should be called narrowed to the head of the message."
170 (goto-char (point-min))
171 (let (alist elem method)
174 (rfc2047-narrow-to-field)
175 (if (not (rfc2047-encodable-p))
177 (if (and (eq (mm-body-7-or-8) '8bit)
180 (car message-posting-charset)))
181 ;; 8 bit must be decoded.
182 (mm-encode-coding-region
183 (point-min) (point-max)
184 (mm-charset-to-coding-system
185 (car message-posting-charset))))
186 ;; No encoding necessary, but folding is nice
189 (goto-char (point-min))
190 (skip-chars-forward "^:")
191 (when (looking-at ": ")
195 ;; We found something that may perhaps be encoded.
197 alist rfc2047-header-encoding-alist)
198 (while (setq elem (pop alist))
199 (when (or (and (stringp (car elem))
200 (looking-at (car elem)))
204 (goto-char (point-min))
205 (re-search-forward "^[^:]+: *" nil t)
207 ((eq method 'address-mime)
208 (rfc2047-encode-region (point) (point-max)))
210 (let (rfc2047-encoding-type)
211 (rfc2047-encode-region (point) (point-max))))
212 ((eq method 'default)
213 (if (and (featurep 'mule)
214 (if (boundp 'default-enable-multibyte-characters)
215 default-enable-multibyte-characters)
217 (mm-encode-coding-region (point) (point-max)
218 mail-parse-charset)))
219 ;; We get this when CC'ing messsages to newsgroups with
220 ;; 8-bit names. The group name mail copy just got
221 ;; unconditionally encoded. Previously, it would ask
222 ;; whether to encode, which was quite confusing for the
223 ;; user. If the new behaviour is wrong, tell me. I have
224 ;; left the old code commented out below.
225 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
226 ;; Modified by Dave Love, with the commented-out code changed
227 ;; in accordance with changes elsewhere.
229 (rfc2047-encode-region (point) (point-max)))
231 ;;; (if (or (message-options-get
232 ;;; 'rfc2047-encode-message-header-encode-any)
233 ;;; (message-options-set
234 ;;; 'rfc2047-encode-message-header-encode-any
236 ;;; "Some texts are not encoded. Encode anyway?")))
237 ;;; (rfc2047-encode-region (point-min) (point-max))
238 ;;; (error "Cannot send unencoded text")))
239 ((mm-coding-system-p method)
240 (if (and (featurep 'mule)
241 (if (boundp 'default-enable-multibyte-characters)
242 default-enable-multibyte-characters))
243 (mm-encode-coding-region (point) (point-max) method)))
246 (goto-char (point-max)))))))
248 ;; Fixme: This, and the require below may not be the Right Thing, but
249 ;; should be safe just before release. -- fx 2001-02-08
250 (eval-when-compile (defvar message-posting-charset))
252 (defun rfc2047-encodable-p ()
253 "Return non-nil if any characters in current buffer need encoding in headers.
254 The buffer may be narrowed."
255 (require 'message) ; for message-posting-charset
257 (mm-find-mime-charset-region (point-min) (point-max))))
259 (not (equal charsets (list (car message-posting-charset)))))))
261 ;; Use this syntax table when parsing into regions that may need
262 ;; encoding. Double quotes are string delimiters, backslash is
263 ;; character quoting, and all other RFC 2822 special characters are
264 ;; treated as punctuation so we can use forward-sexp/forward-word to
265 ;; skip to the end of regions appropriately. Nb. ietf-drums does
266 ;; things differently.
267 (defconst rfc2047-syntax-table
268 ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
269 (let ((table (make-syntax-table)))
270 ;; The following is done to work for setting all elements of the table
271 ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
272 ;; Play safe and don't assume the form of the word syntax entry --
274 (if (fboundp 'set-char-table-range) ; Emacs
275 (funcall (intern "set-char-table-range")
276 table t (aref (standard-syntax-table) ?a))
277 (if (fboundp 'put-char-table)
278 (if (fboundp 'get-char-table) ; warning avoidance
279 (put-char-table t (get-char-table ?a (standard-syntax-table))
281 (modify-syntax-entry ?\\ "\\" table)
282 (modify-syntax-entry ?\" "\"" table)
283 (modify-syntax-entry ?\( "." table)
284 (modify-syntax-entry ?\) "." table)
285 (modify-syntax-entry ?\< "." table)
286 (modify-syntax-entry ?\> "." table)
287 (modify-syntax-entry ?\[ "." table)
288 (modify-syntax-entry ?\] "." table)
289 (modify-syntax-entry ?: "." table)
290 (modify-syntax-entry ?\; "." table)
291 (modify-syntax-entry ?, "." table)
292 (modify-syntax-entry ?@ "." table)
295 (defun rfc2047-encode-region (b e)
296 "Encode words in region B to E that need encoding.
297 By default, the region is treated as containing RFC2822 addresses.
298 Dynamically bind `rfc2047-encoding-type' to change that."
300 (narrow-to-region b e)
301 (if (eq 'mime rfc2047-encoding-type)
302 ;; Simple case -- treat as single word.
304 (goto-char (point-min))
305 ;; Does it need encoding?
306 (skip-chars-forward "\000-\177" e)
308 (rfc2047-encode b e)))
309 ;; `address-mime' case -- take care of quoted words, comments.
310 (with-syntax-table rfc2047-syntax-table
311 (let ((start) ; start of current token
312 end ; end of current token
313 ;; Whether there's an encoded word before the current
314 ;; token, either immediately or separated by space.
316 (goto-char (point-min))
317 (condition-case nil ; in case of unbalanced quotes
318 ;; Look for rfc2822-style: sequences of atoms, quoted
319 ;; strings, specials, whitespace. (Specials mustn't be
324 (unless (= 0 (skip-chars-forward " \t\n"))
325 (setq start (point)))
327 ((not (char-after))) ; eob
329 ((eq ?\" (char-syntax (char-after)))
333 ;; Does it need encoding?
335 (skip-chars-forward "\000-\177" end)
337 (setq last-encoded nil)
338 ;; It needs encoding. Strip the quotes first,
339 ;; since encoded words can't occur in quotes.
341 (delete-backward-char 1)
345 ;; There was a preceding quoted word. We need
346 ;; to include any separating whitespace in this
347 ;; word to avoid it getting lost.
348 (skip-chars-backward " \t")
349 ;; A space is needed between the encoded words.
353 ;; Adjust the end position for the deleted quotes.
354 (rfc2047-encode start (- end 2))
355 (setq last-encoded t))) ; record that it was encoded
356 ((eq ?. (char-syntax (char-after)))
357 ;; Skip other delimiters, but record that they've
358 ;; potentially separated quoted words.
360 (setq last-encoded nil))
361 (t ; normal token/whitespace sequence
364 (skip-chars-backward " \t")
366 ;; Deal with encoding and leading space as for
369 (skip-chars-forward "\000-\177" end)
371 (setq last-encoded nil)
374 (skip-chars-backward " \t")
378 (rfc2047-encode start end)
379 (setq last-encoded t)))))
380 (error (error "Invalid data for rfc2047 encoding: %s"
381 (buffer-substring b e)))))))
382 (rfc2047-fold-region b (point))))
384 (defun rfc2047-encode-string (string)
385 "Encode words in STRING.
386 By default, the string is treated as containing addresses (see
387 `rfc2047-special-chars')."
390 (rfc2047-encode-region (point-min) (point-max))
393 (defun rfc2047-encode (b e)
394 "Encode the word(s) in the region B to E.
395 By default, the region is treated as containing addresses (see
396 `rfc2047-special-chars')."
397 (let* ((mime-charset (mm-find-mime-charset-region b e))
398 (cs (if (> (length mime-charset) 1)
399 ;; Fixme: Instead of this, try to break region into
400 ;; parts that can be encoded separately.
401 (error "Can't rfc2047-encode `%s'"
402 (buffer-substring b e))
403 (setq mime-charset (car mime-charset))
404 (mm-charset-to-coding-system mime-charset)))
405 ;; Fixme: Better, calculate the number of non-ASCII
406 ;; characters, at least for 8-bit charsets.
407 (encoding (if (assq mime-charset
408 rfc2047-charset-encoding-alist)
409 (cdr (assq mime-charset
410 rfc2047-charset-encoding-alist))
413 "=?" (downcase (symbol-name mime-charset)) "?"
414 (downcase (symbol-name encoding)) "?"))
418 (narrow-to-region b e)
419 (when (eq encoding 'B)
420 ;; break into lines before encoding
421 (goto-char (point-min))
423 (goto-char (min (point-max) (+ 15 (point))))
426 (if (and (mm-multibyte-p)
427 (mm-coding-system-p cs))
428 (mm-encode-coding-region (point-min) (point-max) cs))
429 (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
430 (point-min) (point-max))
431 (goto-char (point-min))
439 (forward-line 1))))))
441 (defun rfc2047-fold-field ()
442 "Fold the current header field."
445 (rfc2047-narrow-to-field)
446 (rfc2047-fold-region (point-min) (point-max)))))
448 (defun rfc2047-fold-region (b e)
449 "Fold long lines in region B to E."
451 (narrow-to-region b e)
452 (goto-char (point-min))
456 (bol (save-restriction
458 (rfc2047-point-at-bol))))
460 (when (and (or break qword-break)
461 (> (- (point) bol) 76))
462 (goto-char (or break qword-break))
465 (if (looking-at "[ \t]")
468 (setq bol (1- (point)))
469 ;; Don't break before the first non-LWSP characters.
470 (skip-chars-forward " \t")
474 ((eq (char-after) ?\n)
479 (skip-chars-forward " \t")
480 (unless (or (eobp) (eq (char-after) ?\n))
482 ((eq (char-after) ?\r)
484 ((memq (char-after) '(? ?\t))
485 (skip-chars-forward " \t")
487 ;; Don't break just after the header name.
489 (setq break (1- (point)))))
491 (if (not (looking-at "=\\?[^=]"))
492 (if (eq (char-after) ?=)
494 (skip-chars-forward "^ \t\n\r="))
495 (setq qword-break (point))
496 (skip-chars-forward "^ \t\n\r")))
498 (skip-chars-forward "^ \t\n\r"))))
499 (when (and (or break qword-break)
500 (> (- (point) bol) 76))
501 (goto-char (or break qword-break))
504 (if (looking-at "[ \t]")
507 (setq bol (1- (point)))
508 ;; Don't break before the first non-LWSP characters.
509 (skip-chars-forward " \t")
511 (forward-char 1))))))
513 (defun rfc2047-unfold-field ()
514 "Fold the current line."
517 (rfc2047-narrow-to-field)
518 (rfc2047-unfold-region (point-min) (point-max)))))
520 (defun rfc2047-unfold-region (b e)
521 "Unfold lines in region B to E."
523 (narrow-to-region b e)
524 (goto-char (point-min))
525 (let ((bol (save-restriction
527 (rfc2047-point-at-bol)))
528 (eol (rfc2047-point-at-eol)))
531 (if (and (looking-at "[ \t]")
532 (< (- (rfc2047-point-at-eol) bol) 76))
533 (delete-region eol (progn
535 (skip-chars-forward "\r\n")
537 (setq bol (rfc2047-point-at-bol)))
538 (setq eol (rfc2047-point-at-eol))
541 (defun rfc2047-b-encode-region (b e)
542 "Base64-encode the header contained in region B to E."
544 (narrow-to-region (goto-char b) e)
546 (base64-encode-region (point) (progn (end-of-line) (point)) t)
547 (if (and (bolp) (eolp))
548 (delete-backward-char 1))
551 (defun rfc2047-q-encode-region (b e)
552 "Quoted-printable-encode the header in region B to E."
555 (narrow-to-region (goto-char b) e)
556 (let ((alist rfc2047-q-encoding-alist)
557 (bol (save-restriction
559 (rfc2047-point-at-bol))))
561 (when (looking-at (caar alist))
562 (quoted-printable-encode-region b e nil (cdar alist))
563 (subst-char-in-region (point-min) (point-max) ? ?_)
566 ;; The size of QP encapsulation is about 20, so set limit to
568 (unless (< (- (point-max) (point-min)) 56)
569 ;; Don't break if it could fit in one line.
570 ;; Let rfc2047-encode-region break it later.
571 (goto-char (1+ (point-min)))
572 (while (and (not (bobp)) (not (eobp)))
573 (goto-char (min (point-max) (+ 56 bol)))
574 (search-backward "=" (- (point) 2) t)
575 (unless (or (bobp) (eobp))
577 (setq bol (point)))))))))
580 ;;; Functions for decoding RFC2047 messages
584 (defconst rfc2047-encoded-word-regexp
585 "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\
586 \\?\\([!->@-~ +]*\\)\\?="))
588 ;; Fixme: This should decode in place, not cons intermediate strings.
589 ;; Also check whether it needs to worry about delimiting fields like
592 (defun rfc2047-decode-region (start end)
593 "Decode MIME-encoded words in region between START and END."
595 (let ((case-fold-search t)
599 (narrow-to-region start end)
600 (goto-char (point-min))
601 ;; Remove whitespace between encoded words.
602 (while (re-search-forward
604 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
606 "\\(" rfc2047-encoded-word-regexp "\\)"))
608 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
609 ;; Decode the encoded words.
610 (setq b (goto-char (point-min)))
611 (while (re-search-forward rfc2047-encoded-word-regexp nil t)
612 (setq e (match-beginning 0))
613 (insert (rfc2047-parse-and-decode
616 (delete-region (match-beginning 0) (match-end 0)))))
617 ;; Remove newlines between decoded words, though such things
618 ;; essentially must not be there.
620 (narrow-to-region e (point))
622 (while (re-search-forward "[\n\r]+" nil t)
624 (goto-char (point-max)))
625 (when (and (mm-multibyte-p)
627 (not (eq mail-parse-charset 'us-ascii))
628 (not (eq mail-parse-charset 'gnus-decoded)))
629 (mm-decode-coding-region b e mail-parse-charset))
631 (when (and (mm-multibyte-p)
633 (not (eq mail-parse-charset 'us-ascii))
634 (not (eq mail-parse-charset 'gnus-decoded)))
635 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
637 (defun rfc2047-decode-string (string)
638 "Decode the quoted-printable-encoded STRING and return the results."
639 (let ((m (mm-multibyte-p)))
640 (if (string-match "=\\?" string)
642 ;; Fixme: This logic is wrong, but seems to be required by
643 ;; Gnus summary buffer generation. The value of `m' depends
644 ;; on the current buffer, not global multibyteness or that
645 ;; of the string. Also the string returned should always be
646 ;; multibyte in a multibyte session, i.e. the buffer should
647 ;; be multibyte before `buffer-string' is called.
649 (mm-enable-multibyte))
652 (rfc2047-decode-region (point-min) (point-max)))
654 ;; Fixme: As above, `m' here is inappropriate.
657 (not (eq mail-parse-charset 'us-ascii))
658 (not (eq mail-parse-charset 'gnus-decoded)))
659 (mm-decode-coding-string string mail-parse-charset)
660 (mm-string-as-multibyte string)))))
662 (defun rfc2047-parse-and-decode (word)
663 "Decode WORD and return it if it is an encoded word.
664 Return WORD if it is not not an encoded word or if the charset isn't
666 (if (not (string-match rfc2047-encoded-word-regexp word))
671 (match-string 1 word)
672 (upcase (match-string 2 word))
673 (match-string 3 word))
675 word))) ; un-decodable
677 (defun rfc2047-pad-base64 (string)
678 "Pad STRING to quartets."
679 ;; Be more liberal to accept buggy base64 strings. If
680 ;; base64-decode-string accepts buggy strings, this function could
681 ;; be aliased to identity.
682 (case (mod (length string) 4)
684 (1 string) ;; Error, don't pad it.
685 (2 (concat string "=="))
686 (3 (concat string "="))))
688 (defun rfc2047-decode (charset encoding string)
689 "Decode STRING from the given MIME CHARSET in the given ENCODING.
690 Valid ENCODINGs are \"B\" and \"Q\".
691 If your Emacs implementation can't decode CHARSET, return nil."
692 (if (stringp charset)
693 (setq charset (intern (downcase charset))))
694 (if (or (not charset)
695 (eq 'gnus-all mail-parse-ignored-charsets)
696 (memq 'gnus-all mail-parse-ignored-charsets)
697 (memq charset mail-parse-ignored-charsets))
698 (setq charset mail-parse-charset))
699 (let ((cs (mm-charset-to-coding-system charset)))
700 (if (and (not cs) charset
701 (listp mail-parse-ignored-charsets)
702 (memq 'gnus-unknown mail-parse-ignored-charsets))
703 (setq cs (mm-charset-to-coding-system mail-parse-charset)))
705 (when (and (eq cs 'ascii)
707 (setq cs mail-parse-charset))
708 ;; Fixme: What's this for? The following comment makes no sense. -- fx
709 (mm-with-unibyte-current-buffer
710 ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
711 (mm-decode-coding-string
713 ((equal "B" encoding)
714 (base64-decode-string
715 (rfc2047-pad-base64 string)))
716 ((equal "Q" encoding)
717 (quoted-printable-decode-string
718 (mm-replace-chars-in-string string ?_ ? )))
719 (t (error "Invalid encoding: %s" encoding)))
724 ;;; rfc2047.el ends here