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))
36 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
39 (autoload 'mm-body-7-or-8 "mm-bodies")
41 ;; Avoid gnus-util for mm- code.
42 (defalias 'rfc2047-point-at-bol
43 (if (fboundp 'point-at-bol)
45 'line-beginning-position))
47 (defalias 'rfc2047-point-at-eol
48 (if (fboundp 'point-at-eol)
52 (defvar rfc2047-header-encoding-alist
53 '(("Newsgroups" . nil)
56 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\)" .
59 "*Header/encoding method alist.
60 The list is traversed sequentially. The keys can either be
65 1) nil, in which case no encoding is done;
66 2) `mime', in which case the header will be encoded according to RFC2047;
67 3) `address-mime', like `mime', but takes account of the rules for address
68 fields (where quoted strings and comments must be treated separately);
69 4) a charset, in which case it will be encoded as that charset;
70 5) `default', in which case the field will be encoded as the rest
73 (defvar rfc2047-charset-encoding-alist
96 "Alist of MIME charsets to RFC2047 encodings.
97 Valid encodings are nil, `Q' and `B'. These indicate binary (no) encoding,
98 quoted-printable and base64 respectively.")
100 (defvar rfc2047-encoding-function-alist
101 '((Q . rfc2047-q-encode-region)
102 (B . rfc2047-b-encode-region)
104 "Alist of RFC2047 encodings to encoding functions.")
106 (defvar rfc2047-q-encoding-alist
107 '(("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\):"
109 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
110 ;; Avoid using 8bit characters.
111 ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
112 ("." . "\010\012\014\040-\074\076\100-\136\140-\177"))
113 "Alist of header regexps and valid Q characters.")
116 ;;; Functions for encoding RFC2047 messages
119 (defun rfc2047-narrow-to-field ()
120 "Narrow the buffer to the header on the current line."
126 (if (re-search-forward "^[^ \n\t]" nil t)
131 (goto-char (point-min)))
133 (defun rfc2047-field-value ()
134 "Return the value of the field at point."
137 (rfc2047-narrow-to-field)
138 (re-search-forward ":[ \t\n]*" nil t)
139 (buffer-substring (point) (point-max)))))
141 (defvar rfc2047-encoding-type 'address-mime
142 "The type of encoding done by `rfc2047-encode-region'.
143 This should be dynamically bound around calls to
144 `rfc2047-encode-region' to either `mime' or `address-mime'. See
145 `rfc2047-header-encoding-alist', for definitions.")
147 (defun rfc2047-encode-message-header ()
148 "Encode the message header according to `rfc2047-header-encoding-alist'.
149 Should be called narrowed to the head of the message."
152 (goto-char (point-min))
153 (let (alist elem method)
156 (rfc2047-narrow-to-field)
157 (if (not (rfc2047-encodable-p))
159 (if (and (eq (mm-body-7-or-8) '8bit)
162 (car message-posting-charset)))
163 ;; 8 bit must be decoded.
164 (mm-encode-coding-region
165 (point-min) (point-max)
166 (mm-charset-to-coding-system
167 (car message-posting-charset))))
168 ;; No encoding necessary, but folding is nice
171 (goto-char (point-min))
172 (skip-chars-forward "^:")
173 (when (looking-at ": ")
177 ;; We found something that may perhaps be encoded.
179 alist rfc2047-header-encoding-alist)
180 (while (setq elem (pop alist))
181 (when (or (and (stringp (car elem))
182 (looking-at (car elem)))
186 (goto-char (point-min))
187 (re-search-forward "^[^:]+: *" nil t)
189 ((eq method 'address-mime)
190 (rfc2047-encode-region (point) (point-max)))
192 (let (rfc2047-encoding-type)
193 (rfc2047-encode-region (point) (point-max))))
194 ((eq method 'default)
195 (if (and (featurep 'mule)
196 (if (boundp 'default-enable-multibyte-characters)
197 default-enable-multibyte-characters)
199 (mm-encode-coding-region (point) (point-max)
200 mail-parse-charset)))
201 ;; We get this when CC'ing messsages to newsgroups with
202 ;; 8-bit names. The group name mail copy just got
203 ;; unconditionally encoded. Previously, it would ask
204 ;; whether to encode, which was quite confusing for the
205 ;; user. If the new behaviour is wrong, tell me. I have
206 ;; left the old code commented out below.
207 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
208 ;; Modified by Dave Love, with the commented-out code changed
209 ;; in accordance with changes elsewhere.
211 (rfc2047-encode-region (point) (point-max)))
213 ;;; (if (or (message-options-get
214 ;;; 'rfc2047-encode-message-header-encode-any)
215 ;;; (message-options-set
216 ;;; 'rfc2047-encode-message-header-encode-any
218 ;;; "Some texts are not encoded. Encode anyway?")))
219 ;;; (rfc2047-encode-region (point-min) (point-max))
220 ;;; (error "Cannot send unencoded text")))
221 ((mm-coding-system-p method)
222 (if (and (featurep 'mule)
223 (if (boundp 'default-enable-multibyte-characters)
224 default-enable-multibyte-characters))
225 (mm-encode-coding-region (point) (point-max) method)))
228 (goto-char (point-max)))))))
230 ;; Fixme: This, and the require below may not be the Right Thing, but
231 ;; should be safe just before release. -- fx 2001-02-08
232 (eval-when-compile (defvar message-posting-charset))
234 (defun rfc2047-encodable-p ()
235 "Return non-nil if any characters in current buffer need encoding in headers.
236 The buffer may be narrowed."
237 (require 'message) ; for message-posting-charset
239 (mm-find-mime-charset-region (point-min) (point-max))))
240 (and charsets (not (equal charsets (list message-posting-charset))))))
242 ;; Use this syntax table when parsing into regions that may need
243 ;; encoding. Double quotes are string delimiters, backslash is
244 ;; character quoting, and all other RFC 2822 special characters are
245 ;; treated as punctuation so we can use forward-sexp/forward-word to
246 ;; skip to the end of regions appropriately. Nb. ietf-drums does
247 ;; things differently.
248 (defconst rfc2047-syntax-table
249 ;; This is what we should do, but XEmacs doesn't support the optional
250 ;; arg of `make-syntax-table':
251 ;; (let ((table (make-char-table 'syntax-table '(2))))
252 (let ((table (make-char-table 'syntax-table)))
253 (map-char-table (lambda (k v) (aset table k '(2))) table)
254 (modify-syntax-entry ?\\ "\\" table)
255 (modify-syntax-entry ?\" "\"" table)
256 (modify-syntax-entry ?\( "." table)
257 (modify-syntax-entry ?\) "." table)
258 (modify-syntax-entry ?\< "." table)
259 (modify-syntax-entry ?\> "." table)
260 (modify-syntax-entry ?\[ "." table)
261 (modify-syntax-entry ?\] "." table)
262 (modify-syntax-entry ?: "." table)
263 (modify-syntax-entry ?\; "." table)
264 (modify-syntax-entry ?, "." table)
265 (modify-syntax-entry ?@ "." table)
268 (defun rfc2047-encode-region (b e)
269 "Encode words in region B to E that need encoding.
270 By default, the region is treated as containing RFC2822 addresses.
271 Dynamically bind `rfc2047-encoding-type' to change that."
273 (narrow-to-region b e)
274 (if (eq 'mime rfc2047-encoding-type)
275 ;; Simple case -- treat as single word.
277 (goto-char (point-min))
278 ;; Does it need encoding?
279 (skip-chars-forward "\000-\177" e)
281 (rfc2047-encode b e)))
282 ;; `address-mime' case -- take care of quoted words, comments.
283 (with-syntax-table rfc2047-syntax-table
284 (let ((start) ; start of current token
285 end ; end of current token
286 ;; Whether there's an encoded word before the current
287 ;; token, either immediately or separated by space.
289 (goto-char (point-min))
290 (condition-case nil ; in case of unbalanced quotes
291 ;; Look for rfc2822-style: sequences of atoms, quoted
292 ;; strings, specials, whitespace. (Specials mustn't be
297 (unless (= 0 (skip-chars-forward " \t"))
298 (setq start (point)))
300 ((not (char-after))) ; eob
302 ((eq ?\" (char-syntax (char-after)))
306 ;; Does it need encoding?
308 (skip-chars-forward "\000-\177" end)
310 (setq last-encoded nil)
311 ;; It needs encoding. Strip the quotes first,
312 ;; since encoded words can't occur in quotes.
314 (delete-backward-char 1)
318 ;; There was a preceding quoted word. We need
319 ;; to include any separating whitespace in this
320 ;; word to avoid it getting lost.
321 (skip-chars-backward " \t")
322 ;; A space is needed between the encoded words.
326 ;; Adjust the end position for the deleted quotes.
327 (rfc2047-encode start (- end 2))
328 (setq last-encoded t))) ; record that it was encoded
329 ((eq ?. (char-syntax (char-after)))
330 ;; Skip other delimiters, but record that they've
331 ;; potentially separated quoted words.
333 (setq last-encoded nil))
334 (t ; normal token/whitespace sequence
337 (skip-chars-backward " \t")
339 ;; Deal with encoding and leading space as for
342 (skip-chars-forward "\000-\177" end)
344 (setq last-encoded nil)
347 (skip-chars-backward " \t")
351 (rfc2047-encode start end)
352 (setq last-encoded t)))))
353 (error (error "Invalid data for rfc2047 encoding: %s"
354 (buffer-substring b e)))))))
355 (rfc2047-fold-region b (point))))
357 (defun rfc2047-encode-string (string)
358 "Encode words in STRING.
359 By default, the string is treated as containing addresses (see
360 `rfc2047-special-chars')."
363 (rfc2047-encode-region (point-min) (point-max))
366 (defun rfc2047-encode (b e)
367 "Encode the word(s) in the region B to E.
368 By default, the region is treated as containing addresses (see
369 `rfc2047-special-chars')."
370 (let* ((mime-charset (mm-find-mime-charset-region b e))
371 (cs (if (> (length mime-charset) 1)
372 ;; Fixme: Instead of this, try to break region into
373 ;; parts that can be encoded separately.
374 (error "Can't rfc2047-encode `%s'"
375 (buffer-substring b e))
376 (setq mime-charset (car mime-charset))
377 (mm-charset-to-coding-system mime-charset)))
378 ;; Fixme: Better, calculate the number of non-ASCII
379 ;; characters, at least for 8-bit charsets.
380 (encoding (if (assq mime-charset
381 rfc2047-charset-encoding-alist)
382 (cdr (assq mime-charset
383 rfc2047-charset-encoding-alist))
386 "=?" (downcase (symbol-name mime-charset)) "?"
387 (downcase (symbol-name encoding)) "?"))
391 (narrow-to-region b e)
392 (when (eq encoding 'B)
393 ;; break into lines before encoding
394 (goto-char (point-min))
396 (goto-char (min (point-max) (+ 15 (point))))
399 (if (and (mm-multibyte-p)
400 (mm-coding-system-p cs))
401 (mm-encode-coding-region (point-min) (point-max) cs))
402 (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
403 (point-min) (point-max))
404 (goto-char (point-min))
412 (forward-line 1))))))
414 (defun rfc2047-fold-field ()
415 "Fold the current header field."
418 (rfc2047-narrow-to-field)
419 (rfc2047-fold-region (point-min) (point-max)))))
421 (defun rfc2047-fold-region (b e)
422 "Fold long lines in region B to E."
424 (narrow-to-region b e)
425 (goto-char (point-min))
429 (bol (save-restriction
431 (rfc2047-point-at-bol))))
433 (when (and (or break qword-break)
434 (> (- (point) bol) 76))
435 (goto-char (or break qword-break))
438 (if (looking-at "[ \t]")
441 (setq bol (1- (point)))
442 ;; Don't break before the first non-LWSP characters.
443 (skip-chars-forward " \t")
447 ((eq (char-after) ?\n)
452 (skip-chars-forward " \t")
453 (unless (or (eobp) (eq (char-after) ?\n))
455 ((eq (char-after) ?\r)
457 ((memq (char-after) '(? ?\t))
458 (skip-chars-forward " \t")
460 ;; Don't break just after the header name.
462 (setq break (1- (point)))))
464 (if (not (looking-at "=\\?[^=]"))
465 (if (eq (char-after) ?=)
467 (skip-chars-forward "^ \t\n\r="))
468 (setq qword-break (point))
469 (skip-chars-forward "^ \t\n\r")))
471 (skip-chars-forward "^ \t\n\r"))))
472 (when (and (or break qword-break)
473 (> (- (point) bol) 76))
474 (goto-char (or break qword-break))
477 (if (looking-at "[ \t]")
480 (setq bol (1- (point)))
481 ;; Don't break before the first non-LWSP characters.
482 (skip-chars-forward " \t")
484 (forward-char 1))))))
486 (defun rfc2047-unfold-field ()
487 "Fold the current line."
490 (rfc2047-narrow-to-field)
491 (rfc2047-unfold-region (point-min) (point-max)))))
493 (defun rfc2047-unfold-region (b e)
494 "Unfold lines in region B to E."
496 (narrow-to-region b e)
497 (goto-char (point-min))
498 (let ((bol (save-restriction
500 (rfc2047-point-at-bol)))
501 (eol (rfc2047-point-at-eol))
505 (if (and (looking-at "[ \t]")
506 (< (- (rfc2047-point-at-eol) bol) 76))
507 (delete-region eol (progn
509 (skip-chars-forward "\r\n")
511 (setq bol (rfc2047-point-at-bol)))
512 (setq eol (rfc2047-point-at-eol))
515 (defun rfc2047-b-encode-region (b e)
516 "Base64-encode the header contained in region B to E."
518 (narrow-to-region (goto-char b) e)
520 (base64-encode-region (point) (progn (end-of-line) (point)) t)
521 (if (and (bolp) (eolp))
522 (delete-backward-char 1))
525 (defun rfc2047-q-encode-region (b e)
526 "Quoted-printable-encode the header in region B to E."
529 (narrow-to-region (goto-char b) e)
530 (let ((alist rfc2047-q-encoding-alist)
531 (bol (save-restriction
533 (rfc2047-point-at-bol))))
535 (when (looking-at (caar alist))
536 (quoted-printable-encode-region b e nil (cdar alist))
537 (subst-char-in-region (point-min) (point-max) ? ?_)
540 ;; The size of QP encapsulation is about 20, so set limit to
542 (unless (< (- (point-max) (point-min)) 56)
543 ;; Don't break if it could fit in one line.
544 ;; Let rfc2047-encode-region break it later.
545 (goto-char (1+ (point-min)))
546 (while (and (not (bobp)) (not (eobp)))
547 (goto-char (min (point-max) (+ 56 bol)))
548 (search-backward "=" (- (point) 2) t)
549 (unless (or (bobp) (eobp))
551 (setq bol (point)))))))))
554 ;;; Functions for decoding RFC2047 messages
558 (defconst rfc2047-encoded-word-regexp
559 "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\
560 \\?\\([!->@-~ +]*\\)\\?="))
562 ;; Fixme: This should decode in place, not cons intermediate strings.
563 ;; Also check whether it needs to worry about delimiting fields like
566 (defun rfc2047-decode-region (start end)
567 "Decode MIME-encoded words in region between START and END."
569 (let ((case-fold-search t)
573 (narrow-to-region start end)
574 (goto-char (point-min))
575 ;; Remove whitespace between encoded words.
576 (while (re-search-forward
578 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
580 "\\(" rfc2047-encoded-word-regexp "\\)"))
582 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
583 ;; Decode the encoded words.
584 (setq b (goto-char (point-min)))
585 (while (re-search-forward rfc2047-encoded-word-regexp nil t)
586 (setq e (match-beginning 0))
587 (insert (rfc2047-parse-and-decode
590 (delete-region (match-beginning 0) (match-end 0)))))
591 ;; Remove newlines between decoded words, though such things
592 ;; essentially must not be there.
594 (narrow-to-region e (point))
596 (while (re-search-forward "[\n\r]+" nil t)
598 (goto-char (point-max)))
599 (when (and (mm-multibyte-p)
601 (not (eq mail-parse-charset 'us-ascii))
602 (not (eq mail-parse-charset 'gnus-decoded)))
603 (mm-decode-coding-region b e mail-parse-charset))
605 (when (and (mm-multibyte-p)
607 (not (eq mail-parse-charset 'us-ascii))
608 (not (eq mail-parse-charset 'gnus-decoded)))
609 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
611 (defun rfc2047-decode-string (string)
612 "Decode the quoted-printable-encoded STRING and return the results."
613 (let ((m (mm-multibyte-p)))
614 (if (string-match "=\\?" string)
616 ;; Fixme: This logic is wrong, but seems to be required by
617 ;; Gnus summary buffer generation. The value of `m' depends
618 ;; on the current buffer, not global multibyteness or that
619 ;; of the string. Also the string returned should always be
620 ;; multibyte in a multibyte session, i.e. the buffer should
621 ;; be multibyte before `buffer-string' is called.
623 (mm-enable-multibyte))
626 (rfc2047-decode-region (point-min) (point-max)))
628 ;; Fixme: As above, `m' here is inappropriate.
631 (not (eq mail-parse-charset 'us-ascii))
632 (not (eq mail-parse-charset 'gnus-decoded)))
633 (mm-decode-coding-string string mail-parse-charset)
634 (mm-string-as-multibyte string)))))
636 (defun rfc2047-parse-and-decode (word)
637 "Decode WORD and return it if it is an encoded word.
638 Return WORD if it is not not an encoded word or if the charset isn't
640 (if (not (string-match rfc2047-encoded-word-regexp word))
644 (match-string 1 word)
645 (upcase (match-string 2 word))
646 (match-string 3 word))
649 (defun rfc2047-pad-base64 (string)
650 "Pad STRING to quartets."
651 ;; Be more liberal to accept buggy base64 strings. If
652 ;; base64-decode-string accepts buggy strings, this function could
653 ;; be aliased to identity.
654 (case (mod (length string) 4)
656 (1 string) ;; Error, don't pad it.
657 (2 (concat string "=="))
658 (3 (concat string "="))))
660 (defun rfc2047-decode (charset encoding string)
661 "Decode STRING from the given MIME CHARSET in the given ENCODING.
662 Valid ENCODINGs are \"B\" and \"Q\".
663 If your Emacs implementation can't decode CHARSET, return nil."
664 (if (stringp charset)
665 (setq charset (intern (downcase charset))))
666 (if (or (not charset)
667 (eq 'gnus-all mail-parse-ignored-charsets)
668 (memq 'gnus-all mail-parse-ignored-charsets)
669 (memq charset mail-parse-ignored-charsets))
670 (setq charset mail-parse-charset))
671 (let ((cs (mm-charset-to-coding-system charset)))
672 (if (and (not cs) charset
673 (listp mail-parse-ignored-charsets)
674 (memq 'gnus-unknown mail-parse-ignored-charsets))
675 (setq cs (mm-charset-to-coding-system mail-parse-charset)))
677 (when (and (eq cs 'ascii)
679 (setq cs mail-parse-charset))
680 ;; Fixme: What's this for? The following comment makes no sense. -- fx
681 (mm-with-unibyte-current-buffer
682 ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
683 (mm-decode-coding-string
685 ((equal "B" encoding)
686 (base64-decode-string
687 (rfc2047-pad-base64 string)))
688 ((equal "Q" encoding)
689 (quoted-printable-decode-string
690 (mm-replace-chars-in-string string ?_ ? )))
691 (t (error "Invalid encoding: %s" encoding)))
696 ;;; rfc2047.el ends here