1 ;;; rfc2047.el --- functions for encoding and decoding rfc2047 messages
2 ;; Copyright (C) 1998,1999,2000,02,03,2004 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 (defvar rfc2047-header-encoding-alist
42 '(("Newsgroups\\|Followup-To" . nil
)
44 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\)" .
47 "*Header/encoding method alist.
48 The list is traversed sequentially. The keys can either be
53 1) nil, in which case no encoding is done;
54 2) `mime', in which case the header will be encoded according to RFC2047;
55 3) `address-mime', like `mime', but takes account of the rules for address
56 fields (where quoted strings and comments must be treated separately);
57 4) a charset, in which case it will be encoded as that charset;
58 5) `default', in which case the field will be encoded as the rest
61 (defvar rfc2047-charset-encoding-alist
84 "Alist of MIME charsets to RFC2047 encodings.
85 Valid encodings are nil, `Q' and `B'. These indicate binary (no) encoding,
86 quoted-printable and base64 respectively.")
88 (defvar rfc2047-encoding-function-alist
89 '((Q . rfc2047-q-encode-region
)
90 (B . rfc2047-b-encode-region
)
92 "Alist of RFC2047 encodings to encoding functions.")
94 (defvar rfc2047-q-encoding-alist
95 '(("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|Reply-To\\|Sender\\):"
97 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
98 ;; Avoid using 8bit characters.
99 ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
100 ("." .
"\010\012\014\040-\074\076\100-\136\140-\177"))
101 "Alist of header regexps and valid Q characters.")
104 ;;; Functions for encoding RFC2047 messages
107 (defun rfc2047-narrow-to-field ()
108 "Narrow the buffer to the header on the current line."
114 (if (re-search-forward "^[^ \n\t]" nil t
)
119 (goto-char (point-min)))
121 (defvar rfc2047-encoding-type
'address-mime
122 "The type of encoding done by `rfc2047-encode-region'.
123 This should be dynamically bound around calls to
124 `rfc2047-encode-region' to either `mime' or `address-mime'. See
125 `rfc2047-header-encoding-alist', for definitions.")
127 (defun rfc2047-encode-message-header ()
128 "Encode the message header according to `rfc2047-header-encoding-alist'.
129 Should be called narrowed to the head of the message."
132 (goto-char (point-min))
133 (let (alist elem method
)
136 (rfc2047-narrow-to-field)
137 (if (not (rfc2047-encodable-p))
139 (if (and (eq (mm-body-7-or-8) '8bit
)
142 (car message-posting-charset
)))
143 ;; 8 bit must be decoded.
144 (mm-encode-coding-region
145 (point-min) (point-max)
146 (mm-charset-to-coding-system
147 (car message-posting-charset
))))
148 ;; No encoding necessary, but folding is nice
151 (goto-char (point-min))
152 (skip-chars-forward "^:")
153 (when (looking-at ": ")
157 ;; We found something that may perhaps be encoded.
159 alist rfc2047-header-encoding-alist
)
160 (while (setq elem
(pop alist
))
161 (when (or (and (stringp (car elem
))
162 (looking-at (car elem
)))
166 (goto-char (point-min))
167 (re-search-forward "^[^:]+: *" nil t
)
169 ((eq method
'address-mime
)
170 (rfc2047-encode-region (point) (point-max)))
172 (let ((rfc2047-encoding-type method
))
173 (rfc2047-encode-region (point) (point-max))))
174 ((eq method
'default
)
175 (if (and (featurep 'mule
)
176 (if (boundp 'default-enable-multibyte-characters
)
177 default-enable-multibyte-characters
)
179 (mm-encode-coding-region (point) (point-max)
180 mail-parse-charset
)))
181 ((mm-coding-system-p method
)
182 (if (and (featurep 'mule
)
183 (if (boundp 'default-enable-multibyte-characters
)
184 default-enable-multibyte-characters
))
185 (mm-encode-coding-region (point) (point-max) method
)))
188 (goto-char (point-max)))))))
190 ;; Fixme: This, and the require below may not be the Right Thing, but
191 ;; should be safe just before release. -- fx 2001-02-08
192 (eval-when-compile (defvar message-posting-charset
))
194 (defun rfc2047-encodable-p ()
195 "Return non-nil if any characters in current buffer need encoding in headers.
196 The buffer may be narrowed."
197 (require 'message
) ; for message-posting-charset
199 (mm-find-mime-charset-region (point-min) (point-max))))
200 (and charsets
(not (equal charsets
(list message-posting-charset
))))))
202 ;; Use this syntax table when parsing into regions that may need
203 ;; encoding. Double quotes are string delimiters, backslash is
204 ;; character quoting, and all other RFC 2822 special characters are
205 ;; treated as punctuation so we can use forward-sexp/forward-word to
206 ;; skip to the end of regions appropriately. Nb. ietf-drums does
207 ;; things differently.
208 (defconst rfc2047-syntax-table
209 (let ((table (make-char-table 'syntax-table
'(2))))
210 (modify-syntax-entry ?
\\ "\\" table
)
211 (modify-syntax-entry ?
\" "\"" table
)
212 (modify-syntax-entry ?\
( "." table
)
213 (modify-syntax-entry ?\
) "." table
)
214 (modify-syntax-entry ?\
< "." table
)
215 (modify-syntax-entry ?\
> "." table
)
216 (modify-syntax-entry ?\
[ "." table
)
217 (modify-syntax-entry ?\
] "." table
)
218 (modify-syntax-entry ?
: "." table
)
219 (modify-syntax-entry ?\
; "." table)
220 (modify-syntax-entry ?
, "." table
)
221 (modify-syntax-entry ?
@ "." table
)
224 (defun rfc2047-encode-region (b e
)
225 "Encode words in region B to E that need encoding.
226 By default, the region is treated as containing RFC2822 addresses.
227 Dynamically bind `rfc2047-encoding-type' to change that."
229 (narrow-to-region b e
)
230 (if (eq 'mime rfc2047-encoding-type
)
231 ;; Simple case -- treat as single word.
233 (goto-char (point-min))
234 ;; Does it need encoding?
235 (skip-chars-forward "\000-\177" e
)
237 (rfc2047-encode b e
)))
238 ;; `address-mime' case -- take care of quoted words, comments.
239 (with-syntax-table rfc2047-syntax-table
240 (let ((start (point)) ; start of current token
241 end
; end of current token
242 ;; Whether there's an encoded word before the current
243 ;; token, either immediately or separated by space.
245 (goto-char (point-min))
246 (condition-case nil
; in case of unbalanced quotes
247 ;; Look for rfc2822-style: sequences of atoms, quoted
248 ;; strings, specials, whitespace. (Specials mustn't be
253 (unless (= 0 (skip-chars-forward " \t\n"))
254 (setq start
(point)))
256 ((not (char-after))) ; eob
258 ((eq ?
\" (char-syntax (char-after)))
262 ;; Does it need encoding?
264 (skip-chars-forward "\000-\177" end
)
266 (setq last-encoded nil
)
267 ;; It needs encoding. Strip the quotes first,
268 ;; since encoded words can't occur in quotes.
270 (delete-backward-char 1)
274 ;; There was a preceding quoted word. We need
275 ;; to include any separating whitespace in this
276 ;; word to avoid it getting lost.
277 (skip-chars-backward " \t")
278 ;; A space is needed between the encoded words.
282 ;; Adjust the end position for the deleted quotes.
283 (rfc2047-encode start
(- end
2))
284 (setq last-encoded t
))) ; record that it was encoded
285 ((eq ?.
(char-syntax (char-after)))
286 ;; Skip other delimiters, but record that they've
287 ;; potentially separated quoted words.
289 (setq last-encoded nil
))
290 (t ; normal token/whitespace sequence
293 (skip-chars-backward " \t")
295 ;; Deal with encoding and leading space as for
298 (skip-chars-forward "\000-\177" end
)
300 (setq last-encoded nil
)
303 (skip-chars-backward " \t")
307 (rfc2047-encode start end
)
308 (setq last-encoded t
)))))
309 (error (error "Invalid data for rfc2047 encoding: %s"
310 (buffer-substring b e
)))))))
311 (rfc2047-fold-region b
(point))))
313 (defun rfc2047-encode-string (string)
314 "Encode words in STRING.
315 By default, the string is treated as containing addresses (see
316 `rfc2047-special-chars')."
319 (rfc2047-encode-region (point-min) (point-max))
322 (defun rfc2047-encode (b e
)
323 "Encode the word(s) in the region B to E.
324 By default, the region is treated as containing addresses (see
325 `rfc2047-special-chars')."
326 (let* ((mime-charset (mm-find-mime-charset-region b e
))
327 (cs (if (> (length mime-charset
) 1)
328 ;; Fixme: Instead of this, try to break region into
329 ;; parts that can be encoded separately.
330 (error "Can't rfc2047-encode `%s'"
331 (buffer-substring b e
))
332 (setq mime-charset
(car mime-charset
))
333 (mm-charset-to-coding-system mime-charset
)))
334 ;; Fixme: Better, calculate the number of non-ASCII
335 ;; characters, at least for 8-bit charsets.
336 (encoding (if (assq mime-charset
337 rfc2047-charset-encoding-alist
)
338 (cdr (assq mime-charset
339 rfc2047-charset-encoding-alist
))
342 "=?" (downcase (symbol-name mime-charset
)) "?"
343 (downcase (symbol-name encoding
)) "?"))
347 (narrow-to-region b e
)
348 (when (eq encoding
'B
)
349 ;; break into lines before encoding
350 (goto-char (point-min))
352 (goto-char (min (point-max) (+ 15 (point))))
355 (if (and (mm-multibyte-p)
356 (mm-coding-system-p cs
))
357 (mm-encode-coding-region (point-min) (point-max) cs
))
358 (funcall (cdr (assq encoding rfc2047-encoding-function-alist
))
359 (point-min) (point-max))
360 (goto-char (point-min))
368 (forward-line 1))))))
370 (defun rfc2047-fold-region (b e
)
371 "Fold long lines in region B to E."
373 (narrow-to-region b e
)
374 (goto-char (point-min))
378 (bol (save-restriction
382 (when (and (or break qword-break
) (> (- (point) bol
) 76))
383 (goto-char (or break qword-break
))
386 (if (looking-at "[ \t]")
389 (setq bol
(1- (point)))
390 ;; Don't break before the first non-LWSP characters.
391 (skip-chars-forward " \t")
392 (unless (eobp) (forward-char 1)))
394 ((eq (char-after) ?
\n)
399 (skip-chars-forward " \t")
400 (unless (or (eobp) (eq (char-after) ?
\n))
402 ((eq (char-after) ?
\r)
404 ((memq (char-after) '(? ?
\t))
405 (skip-chars-forward " \t")
407 ;; Don't break just after the header name.
409 (setq break
(1- (point)))))
411 (if (not (looking-at "=\\?[^=]"))
412 (if (eq (char-after) ?
=)
414 (skip-chars-forward "^ \t\n\r="))
415 (setq qword-break
(point))
416 (skip-chars-forward "^ \t\n\r")))
418 (skip-chars-forward "^ \t\n\r"))))
419 (when (and (or break qword-break
) (> (- (point) bol
) 76))
420 (goto-char (or break qword-break
))
423 (if (looking-at "[ \t]")
426 (setq bol
(1- (point)))
427 ;; Don't break before the first non-LWSP characters.
428 (skip-chars-forward " \t")
429 (unless (eobp) (forward-char 1))))))
431 (defun rfc2047-unfold-region (b e
)
432 "Unfold lines in region B to E."
434 (narrow-to-region b e
)
435 (goto-char (point-min))
436 (let ((bol (save-restriction
439 (eol (mm-point-at-eol))
443 (if (and (looking-at "[ \t]")
444 (< (- (mm-point-at-eol) bol
) 76))
445 (delete-region eol
(progn
447 (skip-chars-forward "\r\n")
449 (setq bol
(mm-point-at-bol)))
450 (setq eol
(mm-point-at-eol))
453 (defun rfc2047-b-encode-region (b e
)
454 "Base64-encode the header contained in region B to E."
456 (narrow-to-region (goto-char b
) e
)
458 (base64-encode-region (point) (progn (end-of-line) (point)) t
)
459 (if (and (bolp) (eolp))
460 (delete-backward-char 1))
463 (defun rfc2047-q-encode-region (b e
)
464 "Quoted-printable-encode the header in region B to E."
467 (narrow-to-region (goto-char b
) e
)
468 (let ((alist rfc2047-q-encoding-alist
)
469 (bol (save-restriction
473 (when (looking-at (caar alist
))
474 (quoted-printable-encode-region b e nil
(cdar alist
))
475 (subst-char-in-region (point-min) (point-max) ? ?_
)
478 ;; The size of QP encapsulation is about 20, so set limit to
480 (unless (< (- (point-max) (point-min)) 56)
481 ;; Don't break if it could fit in one line.
482 ;; Let rfc2047-encode-region break it later.
483 (goto-char (1+ (point-min)))
484 (while (and (not (bobp)) (not (eobp)))
485 (goto-char (min (point-max) (+ 56 bol
)))
486 (search-backward "=" (- (point) 2) t
)
487 (unless (or (bobp) (eobp))
489 (setq bol
(point)))))))))
492 ;;; Functions for decoding RFC2047 messages
495 (defvar rfc2047-encoded-word-regexp
496 "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\\?\\([!->@-~ +]+\\)\\?=")
498 (defun rfc2047-decode-region (start end
)
499 "Decode MIME-encoded words in region between START and END."
501 (let ((case-fold-search t
)
505 (narrow-to-region start end
)
506 (goto-char (point-min))
507 ;; Remove whitespace between encoded words.
508 (while (re-search-forward
509 (concat "\\(" rfc2047-encoded-word-regexp
"\\)"
511 "\\(" rfc2047-encoded-word-regexp
"\\)")
513 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
514 ;; Decode the encoded words.
515 (setq b
(goto-char (point-min)))
516 (while (re-search-forward rfc2047-encoded-word-regexp nil t
)
517 (setq e
(match-beginning 0))
518 (insert (rfc2047-parse-and-decode
521 (delete-region (match-beginning 0) (match-end 0)))))
522 (when (and (mm-multibyte-p)
524 (not (eq mail-parse-charset
'gnus-decoded
)))
525 (mm-decode-coding-region b e mail-parse-charset
))
527 (when (and (mm-multibyte-p)
529 (not (eq mail-parse-charset
'us-ascii
))
530 (not (eq mail-parse-charset
'gnus-decoded
)))
531 (mm-decode-coding-region b
(point-max) mail-parse-charset
))
532 (rfc2047-unfold-region (point-min) (point-max))))))
534 (defun rfc2047-decode-string (string)
535 "Decode the quoted-printable-encoded STRING and return the results."
536 (let ((m (mm-multibyte-p)))
539 (mm-enable-multibyte))
542 (rfc2047-decode-region (point-min) (point-max)))
545 (defun rfc2047-parse-and-decode (word)
546 "Decode WORD and return it if it is an encoded word.
548 (if (not (string-match rfc2047-encoded-word-regexp word
))
553 (match-string 1 word
)
554 (upcase (match-string 2 word
))
555 (match-string 3 word
))
559 (defun rfc2047-decode (charset encoding string
)
560 "Decode STRING from the given MIME CHARSET in the given ENCODING.
561 Valid ENCODINGs are \"B\" and \"Q\".
562 If your Emacs implementation can't decode CHARSET, return nil."
563 (if (stringp charset
)
564 (setq charset
(intern (downcase charset
))))
565 (if (or (not charset
)
566 (eq 'gnus-all mail-parse-ignored-charsets
)
567 (memq 'gnus-all mail-parse-ignored-charsets
)
568 (memq charset mail-parse-ignored-charsets
))
569 (setq charset mail-parse-charset
))
570 (let ((cs (mm-charset-to-coding-system charset
)))
571 (if (and (not cs
) charset
572 (listp mail-parse-ignored-charsets
)
573 (memq 'gnus-unknown mail-parse-ignored-charsets
))
574 (setq cs
(mm-charset-to-coding-system mail-parse-charset
)))
576 (when (and (eq cs
'ascii
)
578 (setq cs mail-parse-charset
))
579 ;; Ensure unibyte result in Emacs 20.
580 (let (default-enable-multibyte-characters)
582 (mm-decode-coding-string
584 ((equal "B" encoding
)
585 (base64-decode-string string
))
586 ((equal "Q" encoding
)
587 (quoted-printable-decode-string
588 (mm-replace-chars-in-string string ?_ ?
)))
589 (t (error "Invalid encoding: %s" encoding
)))
594 ;;; arch-tag: a07fe3d4-22b5-4c4a-bd89-b1f82d5d36f6
595 ;;; rfc2047.el ends here