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 (let ((table (make-char-table 'syntax-table '(2))))
250 (modify-syntax-entry ?\\ "\\" table)
251 (modify-syntax-entry ?\" "\"" table)
252 (modify-syntax-entry ?\( "." table)
253 (modify-syntax-entry ?\) "." 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)
264 (defun rfc2047-encode-region (b e)
265 "Encode words in region B to E that need encoding.
266 By default, the region is treated as containing RFC2822 addresses.
267 Dynamically bind `rfc2047-encoding-type' to change that."
269 (narrow-to-region b e)
270 (if (eq 'mime rfc2047-encoding-type)
271 ;; Simple case -- treat as single word.
273 (goto-char (point-min))
274 ;; Does it need encoding?
275 (skip-chars-forward "\000-\177" e)
277 (rfc2047-encode b e)))
278 ;; `address-mime' case -- take care of quoted words, comments.
279 (with-syntax-table rfc2047-syntax-table
280 (let ((start) ; start of current token
281 end ; end of current token
282 ;; Whether there's an encoded word before the current
283 ;; token, either immediately or separated by space.
285 (goto-char (point-min))
286 (condition-case nil ; in case of unbalanced quotes
287 ;; Look for rfc2822-style: sequences of atoms, quoted
288 ;; strings, specials, whitespace. (Specials mustn't be
293 (unless (= 0 (skip-chars-forward " \t"))
294 (setq start (point)))
296 ((not (char-after))) ; eob
298 ((eq ?\" (char-syntax (char-after)))
302 ;; Does it need encoding?
304 (skip-chars-forward "\000-\177" end)
306 (setq last-encoded nil)
307 ;; It needs encoding. Strip the quotes first,
308 ;; since encoded words can't occur in quotes.
310 (delete-backward-char 1)
314 ;; There was a preceding quoted word. We need
315 ;; to include any separating whitespace in this
316 ;; word to avoid it getting lost.
317 (skip-chars-backward " \t")
318 ;; A space is needed between the encoded words.
322 ;; Adjust the end position for the deleted quotes.
323 (rfc2047-encode start (- end 2))
324 (setq last-encoded t))) ; record that it was encoded
325 ((eq ?. (char-syntax (char-after)))
326 ;; Skip other delimiters, but record that they've
327 ;; potentially separated quoted words.
329 (setq last-encoded nil))
330 (t ; normal token/whitespace sequence
333 (skip-chars-backward " \t")
335 ;; Deal with encoding and leading space as for
338 (skip-chars-forward "\000-\177" end)
340 (setq last-encoded nil)
343 (skip-chars-backward " \t")
347 (rfc2047-encode start end)
348 (setq last-encoded t)))))
349 (error (error "Invalid data for rfc2047 encoding: %s"
350 (buffer-substring b e)))))))
351 (rfc2047-fold-region b (point))))
353 (defun rfc2047-encode-string (string)
354 "Encode words in STRING.
355 By default, the string is treated as containing addresses (see
356 `rfc2047-special-chars')."
359 (rfc2047-encode-region (point-min) (point-max))
362 (defun rfc2047-encode (b e)
363 "Encode the word(s) in the region B to E.
364 By default, the region is treated as containing addresses (see
365 `rfc2047-special-chars')."
366 (let* ((mime-charset (mm-find-mime-charset-region b e))
367 (cs (if (> (length mime-charset) 1)
368 ;; Fixme: Instead of this, try to break region into
369 ;; parts that can be encoded separately.
370 (error "Can't rfc2047-encode `%s'"
371 (buffer-substring b e))
372 (setq mime-charset (car mime-charset))
373 (mm-charset-to-coding-system mime-charset)))
374 ;; Fixme: Better, calculate the number of non-ASCII
375 ;; characters, at least for 8-bit charsets.
376 (encoding (if (assq mime-charset
377 rfc2047-charset-encoding-alist)
378 (cdr (assq mime-charset
379 rfc2047-charset-encoding-alist))
382 "=?" (downcase (symbol-name mime-charset)) "?"
383 (downcase (symbol-name encoding)) "?"))
387 (narrow-to-region b e)
388 (when (eq encoding 'B)
389 ;; break into lines before encoding
390 (goto-char (point-min))
392 (goto-char (min (point-max) (+ 15 (point))))
395 (if (and (mm-multibyte-p)
396 (mm-coding-system-p cs))
397 (mm-encode-coding-region (point-min) (point-max) cs))
398 (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
399 (point-min) (point-max))
400 (goto-char (point-min))
408 (forward-line 1))))))
410 (defun rfc2047-fold-region (b e)
411 "Fold long lines in region B to E."
413 (narrow-to-region b e)
414 (goto-char (point-min))
418 (bol (save-restriction
420 (rfc2047-point-at-bol))))
422 (when (and (or break qword-break)
423 (> (- (point) bol) 76))
424 (goto-char (or break qword-break))
427 (if (looking-at "[ \t]")
430 (setq bol (1- (point)))
431 ;; Don't break before the first non-LWSP characters.
432 (skip-chars-forward " \t")
436 ((eq (char-after) ?\n)
441 (skip-chars-forward " \t")
442 (unless (or (eobp) (eq (char-after) ?\n))
444 ((eq (char-after) ?\r)
446 ((memq (char-after) '(? ?\t))
447 (skip-chars-forward " \t")
449 ;; Don't break just after the header name.
451 (setq break (1- (point)))))
453 (if (not (looking-at "=\\?[^=]"))
454 (if (eq (char-after) ?=)
456 (skip-chars-forward "^ \t\n\r="))
457 (setq qword-break (point))
458 (skip-chars-forward "^ \t\n\r")))
460 (skip-chars-forward "^ \t\n\r"))))
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")
473 (forward-char 1))))))
475 (defun rfc2047-unfold-field ()
476 "Fold the current line."
479 (rfc2047-narrow-to-field)
480 (rfc2047-unfold-region (point-min) (point-max)))))
482 (defun rfc2047-unfold-region (b e)
483 "Unfold lines in region B to E."
485 (narrow-to-region b e)
486 (goto-char (point-min))
487 (let ((bol (save-restriction
489 (rfc2047-point-at-bol)))
490 (eol (rfc2047-point-at-eol))
494 (if (and (looking-at "[ \t]")
495 (< (- (rfc2047-point-at-eol) bol) 76))
496 (delete-region eol (progn
498 (skip-chars-forward "\r\n")
500 (setq bol (rfc2047-point-at-bol)))
501 (setq eol (rfc2047-point-at-eol))
504 (defun rfc2047-b-encode-region (b e)
505 "Base64-encode the header contained in region B to E."
507 (narrow-to-region (goto-char b) e)
509 (base64-encode-region (point) (progn (end-of-line) (point)) t)
510 (if (and (bolp) (eolp))
511 (delete-backward-char 1))
514 (defun rfc2047-q-encode-region (b e)
515 "Quoted-printable-encode the header in region B to E."
518 (narrow-to-region (goto-char b) e)
519 (let ((alist rfc2047-q-encoding-alist)
520 (bol (save-restriction
522 (rfc2047-point-at-bol))))
524 (when (looking-at (caar alist))
525 (quoted-printable-encode-region b e nil (cdar alist))
526 (subst-char-in-region (point-min) (point-max) ? ?_)
529 ;; The size of QP encapsulation is about 20, so set limit to
531 (unless (< (- (point-max) (point-min)) 56)
532 ;; Don't break if it could fit in one line.
533 ;; Let rfc2047-encode-region break it later.
534 (goto-char (1+ (point-min)))
535 (while (and (not (bobp)) (not (eobp)))
536 (goto-char (min (point-max) (+ 56 bol)))
537 (search-backward "=" (- (point) 2) t)
538 (unless (or (bobp) (eobp))
540 (setq bol (point)))))))))
543 ;;; Functions for decoding RFC2047 messages
547 (defconst rfc2047-encoded-word-regexp
548 "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\
549 \\?\\([!->@-~ +]*\\)\\?="))
551 ;; Fixme: This should decode in place, not cons intermediate strings.
552 ;; Also check whether it needs to worry about delimiting fields like
555 (defun rfc2047-decode-region (start end)
556 "Decode MIME-encoded words in region between START and END."
558 (let ((case-fold-search t)
562 (narrow-to-region start end)
563 (goto-char (point-min))
564 ;; Remove whitespace between encoded words.
565 (while (re-search-forward
567 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
569 "\\(" rfc2047-encoded-word-regexp "\\)"))
571 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
572 ;; Decode the encoded words.
573 (setq b (goto-char (point-min)))
574 (while (re-search-forward rfc2047-encoded-word-regexp nil t)
575 (setq e (match-beginning 0))
576 (insert (rfc2047-parse-and-decode
579 (delete-region (match-beginning 0) (match-end 0)))))
580 ;; Remove newlines between decoded words, though such things
581 ;; essentially must not be there.
583 (narrow-to-region e (point))
585 (while (re-search-forward "[\n\r]+" nil t)
587 (goto-char (point-max)))
588 (when (and (mm-multibyte-p)
590 (not (eq mail-parse-charset 'us-ascii))
591 (not (eq mail-parse-charset 'gnus-decoded)))
592 (mm-decode-coding-region b e mail-parse-charset))
594 (when (and (mm-multibyte-p)
596 (not (eq mail-parse-charset 'us-ascii))
597 (not (eq mail-parse-charset 'gnus-decoded)))
598 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
600 (defun rfc2047-decode-string (string)
601 "Decode the quoted-printable-encoded STRING and return the results."
602 (let ((m (mm-multibyte-p)))
603 (if (string-match "=\\?" string)
606 (mm-enable-multibyte))
609 (rfc2047-decode-region (point-min) (point-max)))
610 (mm-enable-multibyte)
612 (if (and mail-parse-charset
613 (not (eq mail-parse-charset 'us-ascii))
614 (not (eq mail-parse-charset 'gnus-decoded)))
615 (mm-decode-coding-string string mail-parse-charset)
616 (mm-string-as-multibyte string))))
618 (defun rfc2047-parse-and-decode (word)
619 "Decode WORD and return it if it is an encoded word.
620 Return WORD if it is not not an encoded word or if the charset isn't
622 (if (not (string-match rfc2047-encoded-word-regexp word))
626 (match-string 1 word)
627 (upcase (match-string 2 word))
628 (match-string 3 word))
631 (defun rfc2047-pad-base64 (string)
632 "Pad STRING to quartets."
633 ;; Be more liberal to accept buggy base64 strings. If
634 ;; base64-decode-string accepts buggy strings, this function could
635 ;; be aliased to identity.
636 (case (mod (length string) 4)
638 (1 string) ;; Error, don't pad it.
639 (2 (concat string "=="))
640 (3 (concat string "="))))
642 (defun rfc2047-decode (charset encoding string)
643 "Decode STRING from the given MIME CHARSET in the given ENCODING.
644 Valid ENCODINGs are \"B\" and \"Q\".
645 If your Emacs implementation can't decode CHARSET, return nil."
646 (if (stringp charset)
647 (setq charset (intern (downcase charset))))
648 (if (or (not charset)
649 (eq 'gnus-all mail-parse-ignored-charsets)
650 (memq 'gnus-all mail-parse-ignored-charsets)
651 (memq charset mail-parse-ignored-charsets))
652 (setq charset mail-parse-charset))
653 (let ((cs (mm-charset-to-coding-system charset)))
654 (if (and (not cs) charset
655 (listp mail-parse-ignored-charsets)
656 (memq 'gnus-unknown mail-parse-ignored-charsets))
657 (setq cs (mm-charset-to-coding-system mail-parse-charset)))
659 (when (and (eq cs 'ascii)
661 (setq cs mail-parse-charset))
662 ;; Fixme: What's this for? The following comment makes no sense. -- fx
663 (mm-with-unibyte-current-buffer
664 ;; In Emacs Mule 4, decoding UTF-8 should be in unibyte mode.
665 (mm-decode-coding-string
667 ((equal "B" encoding)
668 (base64-decode-string
669 (rfc2047-pad-base64 string)))
670 ((equal "Q" encoding)
671 (quoted-printable-decode-string
672 (mm-replace-chars-in-string string ?_ ? )))
673 (t (error "Invalid encoding: %s" encoding)))
678 ;;; rfc2047.el ends here