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")
58 ;; Avoid gnus-util for mm- code.
59 (defalias 'rfc2047-point-at-bol
60 (if (fboundp 'point-at-bol)
62 'line-beginning-position))
64 (defalias 'rfc2047-point-at-eol
65 (if (fboundp 'point-at-eol)
69 (defvar rfc2047-header-encoding-alist
70 '(("Newsgroups" . nil)
73 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\)" .
76 "*Header/encoding method alist.
77 The list is traversed sequentially. The keys can either be
82 1) nil, in which case no encoding is done;
83 2) `mime', in which case the header will be encoded according to RFC2047;
84 3) `address-mime', like `mime', but takes account of the rules for address
85 fields (where quoted strings and comments must be treated separately);
86 4) a charset, in which case it will be encoded as that charset;
87 5) `default', in which case the field will be encoded as the rest
90 (defvar rfc2047-charset-encoding-alist
112 (iso-2022-int-1 . B))
113 "Alist of MIME charsets to RFC2047 encodings.
114 Valid encodings are nil, `Q' and `B'. These indicate binary (no) encoding,
115 quoted-printable and base64 respectively.")
117 (defvar rfc2047-encoding-function-alist
118 '((Q . rfc2047-q-encode-region)
119 (B . rfc2047-b-encode-region)
121 "Alist of RFC2047 encodings to encoding functions.")
123 (defvar rfc2047-q-encoding-alist
124 '(("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\):"
126 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
127 ;; Avoid using 8bit characters.
128 ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
129 ("." . "\010\012\014\040-\074\076\100-\136\140-\177"))
130 "Alist of header regexps and valid Q characters.")
133 ;;; Functions for encoding RFC2047 messages
136 (defun rfc2047-narrow-to-field ()
137 "Narrow the buffer to the header on the current line."
143 (if (re-search-forward "^[^ \n\t]" nil t)
148 (goto-char (point-min)))
150 (defun rfc2047-field-value ()
151 "Return the value of the field at point."
154 (rfc2047-narrow-to-field)
155 (re-search-forward ":[ \t\n]*" nil t)
156 (buffer-substring (point) (point-max)))))
158 (defvar rfc2047-encoding-type 'address-mime
159 "The type of encoding done by `rfc2047-encode-region'.
160 This should be dynamically bound around calls to
161 `rfc2047-encode-region' to either `mime' or `address-mime'. See
162 `rfc2047-header-encoding-alist', for definitions.")
164 (defun rfc2047-encode-message-header ()
165 "Encode the message header according to `rfc2047-header-encoding-alist'.
166 Should be called narrowed to the head of the message."
169 (goto-char (point-min))
170 (let (alist elem method)
173 (rfc2047-narrow-to-field)
174 (if (not (rfc2047-encodable-p))
176 (if (and (eq (mm-body-7-or-8) '8bit)
179 (car message-posting-charset)))
180 ;; 8 bit must be decoded.
181 (mm-encode-coding-region
182 (point-min) (point-max)
183 (mm-charset-to-coding-system
184 (car message-posting-charset))))
185 ;; No encoding necessary, but folding is nice
188 (goto-char (point-min))
189 (skip-chars-forward "^:")
190 (when (looking-at ": ")
194 ;; We found something that may perhaps be encoded.
196 alist rfc2047-header-encoding-alist)
197 (while (setq elem (pop alist))
198 (when (or (and (stringp (car elem))
199 (looking-at (car elem)))
203 (goto-char (point-min))
204 (re-search-forward "^[^:]+: *" nil t)
206 ((eq method 'address-mime)
207 (rfc2047-encode-region (point) (point-max)))
209 (let (rfc2047-encoding-type)
210 (rfc2047-encode-region (point) (point-max))))
211 ((eq method 'default)
212 (if (and (featurep 'mule)
213 (if (boundp 'default-enable-multibyte-characters)
214 default-enable-multibyte-characters)
216 (mm-encode-coding-region (point) (point-max)
217 mail-parse-charset)))
218 ;; We get this when CC'ing messsages to newsgroups with
219 ;; 8-bit names. The group name mail copy just got
220 ;; unconditionally encoded. Previously, it would ask
221 ;; whether to encode, which was quite confusing for the
222 ;; user. If the new behaviour is wrong, tell me. I have
223 ;; left the old code commented out below.
224 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
225 ;; Modified by Dave Love, with the commented-out code changed
226 ;; in accordance with changes elsewhere.
228 (rfc2047-encode-region (point) (point-max)))
230 ;;; (if (or (message-options-get
231 ;;; 'rfc2047-encode-message-header-encode-any)
232 ;;; (message-options-set
233 ;;; 'rfc2047-encode-message-header-encode-any
235 ;;; "Some texts are not encoded. Encode anyway?")))
236 ;;; (rfc2047-encode-region (point-min) (point-max))
237 ;;; (error "Cannot send unencoded text")))
238 ((mm-coding-system-p method)
239 (if (and (featurep 'mule)
240 (if (boundp 'default-enable-multibyte-characters)
241 default-enable-multibyte-characters))
242 (mm-encode-coding-region (point) (point-max) method)))
245 (goto-char (point-max)))))))
247 ;; Fixme: This, and the require below may not be the Right Thing, but
248 ;; should be safe just before release. -- fx 2001-02-08
249 (eval-when-compile (defvar message-posting-charset))
251 (defun rfc2047-encodable-p ()
252 "Return non-nil if any characters in current buffer need encoding in headers.
253 The buffer may be narrowed."
254 (require 'message) ; for message-posting-charset
256 (mm-find-mime-charset-region (point-min) (point-max))))
257 (and charsets (not (equal charsets (list message-posting-charset))))))
259 ;; Use this syntax table when parsing into regions that may need
260 ;; encoding. Double quotes are string delimiters, backslash is
261 ;; character quoting, and all other RFC 2822 special characters are
262 ;; treated as punctuation so we can use forward-sexp/forward-word to
263 ;; skip to the end of regions appropriately. Nb. ietf-drums does
264 ;; things differently.
265 (defconst rfc2047-syntax-table
266 ;; This is what we should do, but XEmacs doesn't support the optional
267 ;; arg of `make-syntax-table':
268 ;; (let ((table (make-char-table 'syntax-table '(2))))
269 (let ((table (make-syntax-table)))
270 ;; N.b. this currently doesn't work in Emacs 22.
271 (map-char-table (lambda (k v) (modify-syntax-entry k "w" table)) 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.
295 (goto-char (point-min))
296 ;; Does it need encoding?
297 (skip-chars-forward "\000-\177" e)
299 (rfc2047-encode b e)))
300 ;; `address-mime' case -- take care of quoted words, comments.
301 (with-syntax-table rfc2047-syntax-table
302 (let ((start) ; start of current token
303 end ; end of current token
304 ;; Whether there's an encoded word before the current
305 ;; token, either immediately or separated by space.
307 (goto-char (point-min))
308 (condition-case nil ; in case of unbalanced quotes
309 ;; Look for rfc2822-style: sequences of atoms, quoted
310 ;; strings, specials, whitespace. (Specials mustn't be
315 (unless (= 0 (skip-chars-forward " \t\n"))
316 (setq start (point)))
318 ((not (char-after))) ; eob
320 ((eq ?\" (char-syntax (char-after)))
324 ;; Does it need encoding?
326 (skip-chars-forward "\000-\177" end)
328 (setq last-encoded nil)
329 ;; It needs encoding. Strip the quotes first,
330 ;; since encoded words can't occur in quotes.
332 (delete-backward-char 1)
336 ;; There was a preceding quoted word. We need
337 ;; to include any separating whitespace in this
338 ;; word to avoid it getting lost.
339 (skip-chars-backward " \t")
340 ;; A space is needed between the encoded words.
344 ;; Adjust the end position for the deleted quotes.
345 (rfc2047-encode start (- end 2))
346 (setq last-encoded t))) ; record that it was encoded
347 ((eq ?. (char-syntax (char-after)))
348 ;; Skip other delimiters, but record that they've
349 ;; potentially separated quoted words.
351 (setq last-encoded nil))
352 (t ; normal token/whitespace sequence
355 (skip-chars-backward " \t")
357 ;; Deal with encoding and leading space as for
360 (skip-chars-forward "\000-\177" end)
362 (setq last-encoded nil)
365 (skip-chars-backward " \t")
369 (rfc2047-encode start end)
370 (setq last-encoded t)))))
371 (error (error "Invalid data for rfc2047 encoding: %s"
372 (buffer-substring b e)))))))
373 (rfc2047-fold-region b (point))))
375 (defun rfc2047-encode-string (string)
376 "Encode words in STRING.
377 By default, the string is treated as containing addresses (see
378 `rfc2047-special-chars')."
381 (rfc2047-encode-region (point-min) (point-max))
384 (defun rfc2047-encode (b e)
385 "Encode the word(s) in the region B to E.
386 By default, the region is treated as containing addresses (see
387 `rfc2047-special-chars')."
388 (let* ((mime-charset (mm-find-mime-charset-region b e))
389 (cs (if (> (length mime-charset) 1)
390 ;; Fixme: Instead of this, try to break region into
391 ;; parts that can be encoded separately.
392 (error "Can't rfc2047-encode `%s'"
393 (buffer-substring b e))
394 (setq mime-charset (car mime-charset))
395 (mm-charset-to-coding-system mime-charset)))
396 ;; Fixme: Better, calculate the number of non-ASCII
397 ;; characters, at least for 8-bit charsets.
398 (encoding (if (assq mime-charset
399 rfc2047-charset-encoding-alist)
400 (cdr (assq mime-charset
401 rfc2047-charset-encoding-alist))
404 "=?" (downcase (symbol-name mime-charset)) "?"
405 (downcase (symbol-name encoding)) "?"))
409 (narrow-to-region b e)
410 (when (eq encoding 'B)
411 ;; break into lines before encoding
412 (goto-char (point-min))
414 (goto-char (min (point-max) (+ 15 (point))))
417 (if (and (mm-multibyte-p)
418 (mm-coding-system-p cs))
419 (mm-encode-coding-region (point-min) (point-max) cs))
420 (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
421 (point-min) (point-max))
422 (goto-char (point-min))
430 (forward-line 1))))))
432 (defun rfc2047-fold-field ()
433 "Fold the current header field."
436 (rfc2047-narrow-to-field)
437 (rfc2047-fold-region (point-min) (point-max)))))
439 (defun rfc2047-fold-region (b e)
440 "Fold long lines in region B to E."
442 (narrow-to-region b e)
443 (goto-char (point-min))
447 (bol (save-restriction
449 (rfc2047-point-at-bol))))
451 (when (and (or break qword-break)
452 (> (- (point) bol) 76))
453 (goto-char (or break qword-break))
456 (if (looking-at "[ \t]")
459 (setq bol (1- (point)))
460 ;; Don't break before the first non-LWSP characters.
461 (skip-chars-forward " \t")
465 ((eq (char-after) ?\n)
470 (skip-chars-forward " \t")
471 (unless (or (eobp) (eq (char-after) ?\n))
473 ((eq (char-after) ?\r)
475 ((memq (char-after) '(? ?\t))
476 (skip-chars-forward " \t")
478 ;; Don't break just after the header name.
480 (setq break (1- (point)))))
482 (if (not (looking-at "=\\?[^=]"))
483 (if (eq (char-after) ?=)
485 (skip-chars-forward "^ \t\n\r="))
486 (setq qword-break (point))
487 (skip-chars-forward "^ \t\n\r")))
489 (skip-chars-forward "^ \t\n\r"))))
490 (when (and (or break qword-break)
491 (> (- (point) bol) 76))
492 (goto-char (or break qword-break))
495 (if (looking-at "[ \t]")
498 (setq bol (1- (point)))
499 ;; Don't break before the first non-LWSP characters.
500 (skip-chars-forward " \t")
502 (forward-char 1))))))
504 (defun rfc2047-unfold-field ()
505 "Fold the current line."
508 (rfc2047-narrow-to-field)
509 (rfc2047-unfold-region (point-min) (point-max)))))
511 (defun rfc2047-unfold-region (b e)
512 "Unfold lines in region B to E."
514 (narrow-to-region b e)
515 (goto-char (point-min))
516 (let ((bol (save-restriction
518 (rfc2047-point-at-bol)))
519 (eol (rfc2047-point-at-eol))
523 (if (and (looking-at "[ \t]")
524 (< (- (rfc2047-point-at-eol) bol) 76))
525 (delete-region eol (progn
527 (skip-chars-forward "\r\n")
529 (setq bol (rfc2047-point-at-bol)))
530 (setq eol (rfc2047-point-at-eol))
533 (defun rfc2047-b-encode-region (b e)
534 "Base64-encode the header contained in region B to E."
536 (narrow-to-region (goto-char b) e)
538 (base64-encode-region (point) (progn (end-of-line) (point)) t)
539 (if (and (bolp) (eolp))
540 (delete-backward-char 1))
543 (defun rfc2047-q-encode-region (b e)
544 "Quoted-printable-encode the header in region B to E."
547 (narrow-to-region (goto-char b) e)
548 (let ((alist rfc2047-q-encoding-alist)
549 (bol (save-restriction
551 (rfc2047-point-at-bol))))
553 (when (looking-at (caar alist))
554 (quoted-printable-encode-region b e nil (cdar alist))
555 (subst-char-in-region (point-min) (point-max) ? ?_)
558 ;; The size of QP encapsulation is about 20, so set limit to
560 (unless (< (- (point-max) (point-min)) 56)
561 ;; Don't break if it could fit in one line.
562 ;; Let rfc2047-encode-region break it later.
563 (goto-char (1+ (point-min)))
564 (while (and (not (bobp)) (not (eobp)))
565 (goto-char (min (point-max) (+ 56 bol)))
566 (search-backward "=" (- (point) 2) t)
567 (unless (or (bobp) (eobp))
569 (setq bol (point)))))))))
572 ;;; Functions for decoding RFC2047 messages
576 (defconst rfc2047-encoded-word-regexp
577 "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\
578 \\?\\([!->@-~ +]*\\)\\?="))
580 ;; Fixme: This should decode in place, not cons intermediate strings.
581 ;; Also check whether it needs to worry about delimiting fields like
584 (defun rfc2047-decode-region (start end)
585 "Decode MIME-encoded words in region between START and END."
587 (let ((case-fold-search t)
591 (narrow-to-region start end)
592 (goto-char (point-min))
593 ;; Remove whitespace between encoded words.
594 (while (re-search-forward
596 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
598 "\\(" rfc2047-encoded-word-regexp "\\)"))
600 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
601 ;; Decode the encoded words.
602 (setq b (goto-char (point-min)))
603 (while (re-search-forward rfc2047-encoded-word-regexp nil t)
604 (setq e (match-beginning 0))
605 (insert (rfc2047-parse-and-decode
608 (delete-region (match-beginning 0) (match-end 0)))))
609 ;; Remove newlines between decoded words, though such things
610 ;; essentially must not be there.
612 (narrow-to-region e (point))
614 (while (re-search-forward "[\n\r]+" nil t)
616 (goto-char (point-max)))
617 (when (and (mm-multibyte-p)
619 (not (eq mail-parse-charset 'us-ascii))
620 (not (eq mail-parse-charset 'gnus-decoded)))
621 (mm-decode-coding-region b e mail-parse-charset))
623 (when (and (mm-multibyte-p)
625 (not (eq mail-parse-charset 'us-ascii))
626 (not (eq mail-parse-charset 'gnus-decoded)))
627 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
629 (defun rfc2047-decode-string (string)
630 "Decode the quoted-printable-encoded STRING and return the results."
631 (let ((m (mm-multibyte-p)))
632 (if (string-match "=\\?" string)
634 ;; Fixme: This logic is wrong, but seems to be required by
635 ;; Gnus summary buffer generation. The value of `m' depends
636 ;; on the current buffer, not global multibyteness or that
637 ;; of the string. Also the string returned should always be
638 ;; multibyte in a multibyte session, i.e. the buffer should
639 ;; be multibyte before `buffer-string' is called.
641 (mm-enable-multibyte))
644 (rfc2047-decode-region (point-min) (point-max)))
646 ;; Fixme: As above, `m' here is inappropriate.
649 (not (eq mail-parse-charset 'us-ascii))
650 (not (eq mail-parse-charset 'gnus-decoded)))
651 (mm-decode-coding-string string mail-parse-charset)
652 (mm-string-as-multibyte string)))))
654 (defun rfc2047-parse-and-decode (word)
655 "Decode WORD and return it if it is an encoded word.
656 Return WORD if it is not not an encoded word or if the charset isn't
658 (if (not (string-match rfc2047-encoded-word-regexp word))
663 (match-string 1 word)
664 (upcase (match-string 2 word))
665 (match-string 3 word))
667 word))) ; un-decodable
669 (defun rfc2047-pad-base64 (string)
670 "Pad STRING to quartets."
671 ;; Be more liberal to accept buggy base64 strings. If
672 ;; base64-decode-string accepts buggy strings, this function could
673 ;; be aliased to identity.
674 (case (mod (length string) 4)
676 (1 string) ;; Error, don't pad it.
677 (2 (concat string "=="))
678 (3 (concat string "="))))
680 (defun rfc2047-decode (charset encoding string)
681 "Decode STRING from the given MIME CHARSET in the given ENCODING.
682 Valid ENCODINGs are \"B\" and \"Q\".
683 If your Emacs implementation can't decode CHARSET, return nil."
684 (if (stringp charset)
685 (setq charset (intern (downcase charset))))
686 (if (or (not charset)
687 (eq 'gnus-all mail-parse-ignored-charsets)
688 (memq 'gnus-all mail-parse-ignored-charsets)
689 (memq charset mail-parse-ignored-charsets))
690 (setq charset mail-parse-charset))
691 (let ((cs (mm-charset-to-coding-system charset)))
692 (if (and (not cs) charset
693 (listp mail-parse-ignored-charsets)
694 (memq 'gnus-unknown mail-parse-ignored-charsets))
695 (setq cs (mm-charset-to-coding-system mail-parse-charset)))
697 (when (and (eq cs 'ascii)
699 (setq cs mail-parse-charset))
700 ;; Fixme: What's this for? The following comment makes no sense. -- fx
701 (mm-with-unibyte-current-buffer
702 ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
703 (mm-decode-coding-string
705 ((equal "B" encoding)
706 (base64-decode-string
707 (rfc2047-pad-base64 string)))
708 ((equal "Q" encoding)
709 (quoted-printable-decode-string
710 (mm-replace-chars-in-string string ?_ ? )))
711 (t (error "Invalid encoding: %s" encoding)))
716 ;;; rfc2047.el ends here