Revision: miles@gnu.org--gnu-2005/emacs--cvs-trunk--0--patch-111
[bpt/emacs.git] / lisp / gnus / rfc2047.el
1 ;;; rfc2047.el --- functions for encoding and decoding rfc2047 messages
2
3 ;; Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005
4 ;; Free Software Foundation, Inc.
5
6 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
7 ;; MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; RFC 2047 is "MIME (Multipurpose Internet Mail Extensions) Part
28 ;; Three: Message Header Extensions for Non-ASCII Text".
29
30 ;;; Code:
31
32 (eval-when-compile
33 (require 'cl)
34 (defvar message-posting-charset)
35 (unless (fboundp 'with-syntax-table) ; not in Emacs 20
36 (defmacro with-syntax-table (table &rest body)
37 "Evaluate BODY with syntax table of current buffer set to TABLE.
38 The syntax table of the current buffer is saved, BODY is evaluated, and the
39 saved table is restored, even in case of an abnormal exit.
40 Value is what BODY returns."
41 (let ((old-table (make-symbol "table"))
42 (old-buffer (make-symbol "buffer")))
43 `(let ((,old-table (syntax-table))
44 (,old-buffer (current-buffer)))
45 (unwind-protect
46 (progn
47 (set-syntax-table ,table)
48 ,@body)
49 (save-current-buffer
50 (set-buffer ,old-buffer)
51 (set-syntax-table ,old-table))))))))
52
53 (require 'qp)
54 (require 'mm-util)
55 (require 'ietf-drums)
56 ;; Fixme: Avoid this (used for mail-parse-charset) mm dependence on gnus.
57 (require 'mail-prsvr)
58 (require 'base64)
59 (autoload 'mm-body-7-or-8 "mm-bodies")
60
61 (eval-and-compile
62 ;; Avoid gnus-util for mm- code.
63 (defalias 'rfc2047-point-at-bol
64 (if (fboundp 'point-at-bol)
65 'point-at-bol
66 'line-beginning-position))
67
68 (defalias 'rfc2047-point-at-eol
69 (if (fboundp 'point-at-eol)
70 'point-at-eol
71 'line-end-position)))
72
73 (defvar rfc2047-header-encoding-alist
74 '(("Newsgroups" . nil)
75 ("Followup-To" . nil)
76 ("Message-ID" . nil)
77 ("\\(Resent-\\)?\\(From\\|Cc\\|To\\|Bcc\\|\\(In-\\)?Reply-To\\|Sender\
78 \\|Mail-Followup-To\\|Mail-Copies-To\\|Approved\\)" . address-mime)
79 (t . mime))
80 "*Header/encoding method alist.
81 The list is traversed sequentially. The keys can either be
82 header regexps or t.
83
84 The values can be:
85
86 1) nil, in which case no encoding is done;
87 2) `mime', in which case the header will be encoded according to RFC2047;
88 3) `address-mime', like `mime', but takes account of the rules for address
89 fields (where quoted strings and comments must be treated separately);
90 4) a charset, in which case it will be encoded as that charset;
91 5) `default', in which case the field will be encoded as the rest
92 of the article.")
93
94 (defvar rfc2047-charset-encoding-alist
95 '((us-ascii . nil)
96 (iso-8859-1 . Q)
97 (iso-8859-2 . Q)
98 (iso-8859-3 . Q)
99 (iso-8859-4 . Q)
100 (iso-8859-5 . B)
101 (koi8-r . B)
102 (iso-8859-7 . B)
103 (iso-8859-8 . B)
104 (iso-8859-9 . Q)
105 (iso-8859-14 . Q)
106 (iso-8859-15 . Q)
107 (iso-2022-jp . B)
108 (iso-2022-kr . B)
109 (gb2312 . B)
110 (big5 . B)
111 (cn-big5 . B)
112 (cn-gb . B)
113 (cn-gb-2312 . B)
114 (euc-kr . B)
115 (iso-2022-jp-2 . B)
116 (iso-2022-int-1 . B)
117 (viscii . Q))
118 "Alist of MIME charsets to RFC2047 encodings.
119 Valid encodings are nil, `Q' and `B'. These indicate binary (no) encoding,
120 quoted-printable and base64 respectively.")
121
122 (defvar rfc2047-encoding-function-alist
123 '((Q . rfc2047-q-encode-region)
124 (B . rfc2047-b-encode-region)
125 (nil . ignore))
126 "Alist of RFC2047 encodings to encoding functions.")
127
128 ;;;
129 ;;; Functions for encoding RFC2047 messages
130 ;;;
131
132 (defun rfc2047-qp-or-base64 ()
133 "Return the type with which to encode the buffer.
134 This is either `base64' or `quoted-printable'."
135 (save-excursion
136 (let ((limit (min (point-max) (+ 2000 (point-min))))
137 (n8bit 0))
138 (goto-char (point-min))
139 (skip-chars-forward "\x20-\x7f\r\n\t" limit)
140 (while (< (point) limit)
141 (incf n8bit)
142 (forward-char 1)
143 (skip-chars-forward "\x20-\x7f\r\n\t" limit))
144 (if (or (< (* 6 n8bit) (- limit (point-min)))
145 ;; Don't base64, say, a short line with a single
146 ;; non-ASCII char when splitting parts by charset.
147 (= n8bit 1))
148 'quoted-printable
149 'base64))))
150
151 (defun rfc2047-narrow-to-field ()
152 "Narrow the buffer to the header on the current line."
153 (beginning-of-line)
154 (narrow-to-region
155 (point)
156 (progn
157 (forward-line 1)
158 (if (re-search-forward "^[^ \n\t]" nil t)
159 (rfc2047-point-at-bol)
160 (point-max))))
161 (goto-char (point-min)))
162
163 (defun rfc2047-field-value ()
164 "Return the value of the field at point."
165 (save-excursion
166 (save-restriction
167 (rfc2047-narrow-to-field)
168 (re-search-forward ":[ \t\n]*" nil t)
169 (buffer-substring (point) (point-max)))))
170
171 (defvar rfc2047-encoding-type 'address-mime
172 "The type of encoding done by `rfc2047-encode-region'.
173 This should be dynamically bound around calls to
174 `rfc2047-encode-region' to either `mime' or `address-mime'. See
175 `rfc2047-header-encoding-alist', for definitions.")
176
177 (defun rfc2047-encode-message-header ()
178 "Encode the message header according to `rfc2047-header-encoding-alist'.
179 Should be called narrowed to the head of the message."
180 (interactive "*")
181 (save-excursion
182 (goto-char (point-min))
183 (let (alist elem method)
184 (while (not (eobp))
185 (save-restriction
186 (rfc2047-narrow-to-field)
187 (if (not (rfc2047-encodable-p))
188 (prog1
189 (if (and (eq (mm-body-7-or-8) '8bit)
190 (mm-multibyte-p)
191 (mm-coding-system-p
192 (car message-posting-charset)))
193 ;; 8 bit must be decoded.
194 (mm-encode-coding-region
195 (point-min) (point-max)
196 (mm-charset-to-coding-system
197 (car message-posting-charset))))
198 ;; No encoding necessary, but folding is nice
199 (rfc2047-fold-region
200 (save-excursion
201 (goto-char (point-min))
202 (skip-chars-forward "^:")
203 (when (looking-at ": ")
204 (forward-char 2))
205 (point))
206 (point-max)))
207 ;; We found something that may perhaps be encoded.
208 (setq method nil
209 alist rfc2047-header-encoding-alist)
210 (while (setq elem (pop alist))
211 (when (or (and (stringp (car elem))
212 (looking-at (car elem)))
213 (eq (car elem) t))
214 (setq alist nil
215 method (cdr elem))))
216 (goto-char (point-min))
217 (re-search-forward "^[^:]+: *" nil t)
218 (cond
219 ((eq method 'address-mime)
220 (rfc2047-encode-region (point) (point-max)))
221 ((eq method 'mime)
222 (let ((rfc2047-encoding-type 'mime))
223 (rfc2047-encode-region (point) (point-max))))
224 ((eq method 'default)
225 (if (and (featurep 'mule)
226 (if (boundp 'default-enable-multibyte-characters)
227 default-enable-multibyte-characters)
228 mail-parse-charset)
229 (mm-encode-coding-region (point) (point-max)
230 mail-parse-charset)))
231 ;; We get this when CC'ing messsages to newsgroups with
232 ;; 8-bit names. The group name mail copy just got
233 ;; unconditionally encoded. Previously, it would ask
234 ;; whether to encode, which was quite confusing for the
235 ;; user. If the new behaviour is wrong, tell me. I have
236 ;; left the old code commented out below.
237 ;; -- Per Abrahamsen <abraham@dina.kvl.dk> Date: 2001-10-07.
238 ;; Modified by Dave Love, with the commented-out code changed
239 ;; in accordance with changes elsewhere.
240 ((null method)
241 (rfc2047-encode-region (point) (point-max)))
242 ;;; ((null method)
243 ;;; (if (or (message-options-get
244 ;;; 'rfc2047-encode-message-header-encode-any)
245 ;;; (message-options-set
246 ;;; 'rfc2047-encode-message-header-encode-any
247 ;;; (y-or-n-p
248 ;;; "Some texts are not encoded. Encode anyway?")))
249 ;;; (rfc2047-encode-region (point-min) (point-max))
250 ;;; (error "Cannot send unencoded text")))
251 ((mm-coding-system-p method)
252 (if (and (featurep 'mule)
253 (if (boundp 'default-enable-multibyte-characters)
254 default-enable-multibyte-characters))
255 (mm-encode-coding-region (point) (point-max) method)))
256 ;; Hm.
257 (t)))
258 (goto-char (point-max)))))))
259
260 ;; Fixme: This, and the require below may not be the Right Thing, but
261 ;; should be safe just before release. -- fx 2001-02-08
262 (eval-when-compile (defvar message-posting-charset))
263
264 (defun rfc2047-encodable-p ()
265 "Return non-nil if any characters in current buffer need encoding in headers.
266 The buffer may be narrowed."
267 (require 'message) ; for message-posting-charset
268 (let ((charsets
269 (mm-find-mime-charset-region (point-min) (point-max))))
270 (and charsets
271 (not (equal charsets (list (car message-posting-charset)))))))
272
273 ;; Use this syntax table when parsing into regions that may need
274 ;; encoding. Double quotes are string delimiters, backslash is
275 ;; character quoting, and all other RFC 2822 special characters are
276 ;; treated as punctuation so we can use forward-sexp/forward-word to
277 ;; skip to the end of regions appropriately. Nb. ietf-drums does
278 ;; things differently.
279 (defconst rfc2047-syntax-table
280 ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
281 (let ((table (make-syntax-table)))
282 ;; The following is done to work for setting all elements of the table
283 ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
284 ;; Play safe and don't assume the form of the word syntax entry --
285 ;; copy it from ?a.
286 (if (fboundp 'set-char-table-range) ; Emacs
287 (funcall (intern "set-char-table-range")
288 table t (aref (standard-syntax-table) ?a))
289 (if (fboundp 'put-char-table)
290 (if (fboundp 'get-char-table) ; warning avoidance
291 (put-char-table t (get-char-table ?a (standard-syntax-table))
292 table))))
293 (modify-syntax-entry ?\\ "\\" table)
294 (modify-syntax-entry ?\" "\"" table)
295 (modify-syntax-entry ?\( "." table)
296 (modify-syntax-entry ?\) "." table)
297 (modify-syntax-entry ?\< "." table)
298 (modify-syntax-entry ?\> "." table)
299 (modify-syntax-entry ?\[ "." table)
300 (modify-syntax-entry ?\] "." table)
301 (modify-syntax-entry ?: "." table)
302 (modify-syntax-entry ?\; "." table)
303 (modify-syntax-entry ?, "." table)
304 (modify-syntax-entry ?@ "." table)
305 table))
306
307 (defun rfc2047-encode-region (b e)
308 "Encode words in region B to E that need encoding.
309 By default, the region is treated as containing RFC2822 addresses.
310 Dynamically bind `rfc2047-encoding-type' to change that."
311 (save-restriction
312 (narrow-to-region b e)
313 (if (eq 'mime rfc2047-encoding-type)
314 ;; Simple case. Treat as single word after any initial ASCII
315 ;; part and before any tailing ASCII part. The leading ASCII
316 ;; is relevant for instance in Subject headers with `Re:' for
317 ;; interoperability with non-MIME clients, and we might as
318 ;; well avoid the tail too.
319 (progn
320 (goto-char (point-min))
321 ;; Does it need encoding?
322 (skip-chars-forward "\000-\177")
323 (unless (eobp)
324 (skip-chars-backward "^ \n") ; beginning of space-delimited word
325 (rfc2047-encode (point) (progn
326 (goto-char e)
327 (skip-chars-backward "\000-\177")
328 (skip-chars-forward "^ \n")
329 ;; end of space-delimited word
330 (point)))))
331 ;; `address-mime' case -- take care of quoted words, comments.
332 (with-syntax-table rfc2047-syntax-table
333 (let ((start) ; start of current token
334 end ; end of current token
335 ;; Whether there's an encoded word before the current
336 ;; token, either immediately or separated by space.
337 last-encoded)
338 (goto-char (point-min))
339 (condition-case nil ; in case of unbalanced quotes
340 ;; Look for rfc2822-style: sequences of atoms, quoted
341 ;; strings, specials, whitespace. (Specials mustn't be
342 ;; encoded.)
343 (while (not (eobp))
344 (setq start (point))
345 ;; Skip whitespace.
346 (unless (= 0 (skip-chars-forward " \t\n"))
347 (setq start (point)))
348 (cond
349 ((not (char-after))) ; eob
350 ;; else token start
351 ((eq ?\" (char-syntax (char-after)))
352 ;; Quoted word.
353 (forward-sexp)
354 (setq end (point))
355 ;; Does it need encoding?
356 (goto-char start)
357 (skip-chars-forward "\000-\177" end)
358 (if (= end (point))
359 (setq last-encoded nil)
360 ;; It needs encoding. Strip the quotes first,
361 ;; since encoded words can't occur in quotes.
362 (goto-char end)
363 (delete-backward-char 1)
364 (goto-char start)
365 (delete-char 1)
366 (when last-encoded
367 ;; There was a preceding quoted word. We need
368 ;; to include any separating whitespace in this
369 ;; word to avoid it getting lost.
370 (skip-chars-backward " \t")
371 ;; A space is needed between the encoded words.
372 (insert ? )
373 (setq start (point)
374 end (1+ end)))
375 ;; Adjust the end position for the deleted quotes.
376 (rfc2047-encode start (- end 2))
377 (setq last-encoded t))) ; record that it was encoded
378 ((eq ?. (char-syntax (char-after)))
379 ;; Skip other delimiters, but record that they've
380 ;; potentially separated quoted words.
381 (forward-char)
382 (setq last-encoded nil))
383 (t ; normal token/whitespace sequence
384 ;; Find the end.
385 (forward-word 1)
386 (skip-chars-backward " \t")
387 (setq end (point))
388 ;; Deal with encoding and leading space as for
389 ;; quoted words.
390 (goto-char start)
391 (skip-chars-forward "\000-\177" end)
392 (if (= end (point))
393 (setq last-encoded nil)
394 (when last-encoded
395 (goto-char start)
396 (skip-chars-backward " \t")
397 (insert ? )
398 (setq start (point)
399 end (1+ end)))
400 (rfc2047-encode start end)
401 (setq last-encoded t)))))
402 (error
403 (error "Invalid data for rfc2047 encoding: %s"
404 (buffer-substring b e)))))))
405 (rfc2047-fold-region b (point))))
406
407 (defun rfc2047-encode-string (string)
408 "Encode words in STRING.
409 By default, the string is treated as containing addresses (see
410 `rfc2047-encoding-type')."
411 (with-temp-buffer
412 (insert string)
413 (rfc2047-encode-region (point-min) (point-max))
414 (buffer-string)))
415
416 (defun rfc2047-encode (b e)
417 "Encode the word(s) in the region B to E.
418 By default, the region is treated as containing addresses (see
419 `rfc2047-encoding-type')."
420 (let* ((mime-charset (mm-find-mime-charset-region b e))
421 (cs (if (> (length mime-charset) 1)
422 ;; Fixme: Instead of this, try to break region into
423 ;; parts that can be encoded separately.
424 (error "Can't rfc2047-encode `%s'"
425 (buffer-substring b e))
426 (setq mime-charset (car mime-charset))
427 (mm-charset-to-coding-system mime-charset)))
428 ;; Fixme: Better, calculate the number of non-ASCII
429 ;; characters, at least for 8-bit charsets.
430 (encoding (or (cdr (assq mime-charset
431 rfc2047-charset-encoding-alist))
432 ;; For the charsets that don't have a preferred
433 ;; encoding, choose the one that's shorter.
434 (save-restriction
435 (narrow-to-region b e)
436 (if (eq (rfc2047-qp-or-base64) 'base64)
437 'B
438 'Q))))
439 (start (concat
440 "=?" (downcase (symbol-name mime-charset)) "?"
441 (downcase (symbol-name encoding)) "?"))
442 (factor (case mime-charset
443 ((iso-8859-5 iso-8859-7 iso-8859-8 koi8-r) 1)
444 ((big5 gb2312 euc-kr) 2)
445 (utf-8 4)
446 (t 8)))
447 (pre (- b (save-restriction
448 (widen)
449 (rfc2047-point-at-bol))))
450 ;; encoded-words must not be longer than 75 characters,
451 ;; including charset, encoding etc. This leaves us with
452 ;; 75 - (length start) - 2 - 2 characters. The last 2 is for
453 ;; possible base64 padding. In the worst case (iso-2022-*)
454 ;; each character expands to 8 bytes which is expanded by a
455 ;; factor of 4/3 by base64 encoding.
456 (length (floor (- 75 (length start) 4) (* factor (/ 4.0 3.0))))
457 ;; Limit line length to 76 characters.
458 (length1 (max 1 (floor (- 76 (length start) 4 pre)
459 (* factor (/ 4.0 3.0)))))
460 (first t))
461 (if mime-charset
462 (save-restriction
463 (narrow-to-region b e)
464 (when (eq encoding 'B)
465 ;; break into lines before encoding
466 (goto-char (point-min))
467 (while (not (eobp))
468 (if first
469 (progn
470 (goto-char (min (point-max) (+ length1 (point))))
471 (setq first nil))
472 (goto-char (min (point-max) (+ length (point)))))
473 (unless (eobp)
474 (insert ?\n)))
475 (setq first t))
476 (if (and (mm-multibyte-p)
477 (mm-coding-system-p cs))
478 (mm-encode-coding-region (point-min) (point-max) cs))
479 (funcall (cdr (assq encoding rfc2047-encoding-function-alist))
480 (point-min) (point-max))
481 (goto-char (point-min))
482 (while (not (eobp))
483 (unless first
484 (insert ? ))
485 (setq first nil)
486 (insert start)
487 (end-of-line)
488 (insert "?=")
489 (forward-line 1))))))
490
491 (defun rfc2047-fold-field ()
492 "Fold the current header field."
493 (save-excursion
494 (save-restriction
495 (rfc2047-narrow-to-field)
496 (rfc2047-fold-region (point-min) (point-max)))))
497
498 (defun rfc2047-fold-region (b e)
499 "Fold long lines in region B to E."
500 (save-restriction
501 (narrow-to-region b e)
502 (goto-char (point-min))
503 (let ((break nil)
504 (qword-break nil)
505 (first t)
506 (bol (save-restriction
507 (widen)
508 (rfc2047-point-at-bol))))
509 (while (not (eobp))
510 (when (and (or break qword-break)
511 (> (- (point) bol) 76))
512 (goto-char (or break qword-break))
513 (setq break nil
514 qword-break nil)
515 (if (looking-at "[ \t]")
516 (insert ?\n)
517 (insert "\n "))
518 (setq bol (1- (point)))
519 ;; Don't break before the first non-LWSP characters.
520 (skip-chars-forward " \t")
521 (unless (eobp)
522 (forward-char 1)))
523 (cond
524 ((eq (char-after) ?\n)
525 (forward-char 1)
526 (setq bol (point)
527 break nil
528 qword-break nil)
529 (skip-chars-forward " \t")
530 (unless (or (eobp) (eq (char-after) ?\n))
531 (forward-char 1)))
532 ((eq (char-after) ?\r)
533 (forward-char 1))
534 ((memq (char-after) '(? ?\t))
535 (skip-chars-forward " \t")
536 (if first
537 ;; Don't break just after the header name.
538 (setq first nil)
539 (setq break (1- (point)))))
540 ((not break)
541 (if (not (looking-at "=\\?[^=]"))
542 (if (eq (char-after) ?=)
543 (forward-char 1)
544 (skip-chars-forward "^ \t\n\r="))
545 ;; Don't break at the start of the field.
546 (unless (= (point) b)
547 (setq qword-break (point)))
548 (skip-chars-forward "^ \t\n\r")))
549 (t
550 (skip-chars-forward "^ \t\n\r"))))
551 (when (and (or break qword-break)
552 (> (- (point) bol) 76))
553 (goto-char (or break qword-break))
554 (setq break nil
555 qword-break nil)
556 (if (looking-at "[ \t]")
557 (insert ?\n)
558 (insert "\n "))
559 (setq bol (1- (point)))
560 ;; Don't break before the first non-LWSP characters.
561 (skip-chars-forward " \t")
562 (unless (eobp)
563 (forward-char 1))))))
564
565 (defun rfc2047-unfold-field ()
566 "Fold the current line."
567 (save-excursion
568 (save-restriction
569 (rfc2047-narrow-to-field)
570 (rfc2047-unfold-region (point-min) (point-max)))))
571
572 (defun rfc2047-unfold-region (b e)
573 "Unfold lines in region B to E."
574 (save-restriction
575 (narrow-to-region b e)
576 (goto-char (point-min))
577 (let ((bol (save-restriction
578 (widen)
579 (rfc2047-point-at-bol)))
580 (eol (rfc2047-point-at-eol)))
581 (forward-line 1)
582 (while (not (eobp))
583 (if (and (looking-at "[ \t]")
584 (< (- (rfc2047-point-at-eol) bol) 76))
585 (delete-region eol (progn
586 (goto-char eol)
587 (skip-chars-forward "\r\n")
588 (point)))
589 (setq bol (rfc2047-point-at-bol)))
590 (setq eol (rfc2047-point-at-eol))
591 (forward-line 1)))))
592
593 (defun rfc2047-b-encode-region (b e)
594 "Base64-encode the header contained in region B to E."
595 (save-restriction
596 (narrow-to-region (goto-char b) e)
597 (while (not (eobp))
598 (base64-encode-region (point) (progn (end-of-line) (point)) t)
599 (if (and (bolp) (eolp))
600 (delete-backward-char 1))
601 (forward-line))))
602
603 (defun rfc2047-q-encode-region (b e)
604 "Quoted-printable-encode the header in region B to E."
605 (save-excursion
606 (save-restriction
607 (narrow-to-region (goto-char b) e)
608 (let ((bol (save-restriction
609 (widen)
610 (rfc2047-point-at-bol))))
611 (quoted-printable-encode-region
612 b e nil
613 ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
614 ;; Avoid using 8bit characters.
615 ;; This list excludes `especials' (see the RFC2047 syntax),
616 ;; meaning that some characters in non-structured fields will
617 ;; get encoded when they con't need to be. The following is
618 ;; what it used to be.
619 ;;; ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
620 ;;; "\010\012\014\040-\074\076\100-\136\140-\177")
621 "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
622 (subst-char-in-region (point-min) (point-max) ? ?_)
623 ;; The size of QP encapsulation is about 20, so set limit to
624 ;; 56=76-20.
625 (unless (< (- (point-max) (point-min)) 56)
626 ;; Don't break if it could fit in one line.
627 ;; Let rfc2047-encode-region break it later.
628 (goto-char (1+ (point-min)))
629 (while (and (not (bobp)) (not (eobp)))
630 (goto-char (min (point-max) (+ 56 bol)))
631 (search-backward "=" (- (point) 2) t)
632 (unless (or (bobp) (eobp))
633 (insert ?\n)
634 (setq bol (point)))))))))
635
636 ;;;
637 ;;; Functions for decoding RFC2047 messages
638 ;;;
639
640 (eval-and-compile
641 (defconst rfc2047-encoded-word-regexp
642 "=\\?\\([^][\000-\040()<>@,\;:\\\"/?.=]+\\)\\?\\(B\\|Q\\)\
643 \\?\\([!->@-~ +]*\\)\\?="))
644
645 (defvar rfc2047-quote-decoded-words-containing-tspecials nil
646 "If non-nil, quote decoded words containing special characters.")
647
648 ;; Fixme: This should decode in place, not cons intermediate strings.
649 ;; Also check whether it needs to worry about delimiting fields like
650 ;; encoding.
651
652 ;; In fact it's reported that (invalid) encoding of mailboxes in
653 ;; addr-specs is in use, so delimiting fields might help. Probably
654 ;; not decoding a word which isn't properly delimited is good enough
655 ;; and worthwhile (is it more correct or not?), e.g. something like
656 ;; `=?iso-8859-1?q?foo?=@'.
657
658 (defun rfc2047-decode-region (start end)
659 "Decode MIME-encoded words in region between START and END."
660 (interactive "r")
661 (let ((case-fold-search t)
662 b e)
663 (save-excursion
664 (save-restriction
665 (narrow-to-region start end)
666 (goto-char (point-min))
667 ;; Remove whitespace between encoded words.
668 (while (re-search-forward
669 (eval-when-compile
670 (concat "\\(" rfc2047-encoded-word-regexp "\\)"
671 "\\(\n?[ \t]\\)+"
672 "\\(" rfc2047-encoded-word-regexp "\\)"))
673 nil t)
674 (delete-region (goto-char (match-end 1)) (match-beginning 6)))
675 ;; Decode the encoded words.
676 (setq b (goto-char (point-min)))
677 (while (re-search-forward rfc2047-encoded-word-regexp nil t)
678 (setq e (match-beginning 0))
679 (insert (rfc2047-parse-and-decode
680 (prog1
681 (match-string 0)
682 (delete-region e (match-end 0)))))
683 (while (looking-at rfc2047-encoded-word-regexp)
684 (insert (rfc2047-parse-and-decode
685 (prog1
686 (match-string 0)
687 (delete-region (point) (match-end 0))))))
688 (save-restriction
689 (narrow-to-region e (point))
690 (goto-char e)
691 ;; Remove newlines between decoded words, though such
692 ;; things essentially must not be there.
693 (while (re-search-forward "[\n\r]+" nil t)
694 (replace-match " "))
695 ;; Quote decoded words if there are special characters
696 ;; which might violate RFC2822.
697 (when (and rfc2047-quote-decoded-words-containing-tspecials
698 (let ((regexp (car (rassq
699 'address-mime
700 rfc2047-header-encoding-alist))))
701 (when regexp
702 (save-restriction
703 (widen)
704 (beginning-of-line)
705 (while (and (memq (char-after) '(? ?\t))
706 (zerop (forward-line -1))))
707 (looking-at regexp)))))
708 (let (quoted)
709 (goto-char e)
710 (skip-chars-forward " \t")
711 (setq start (point))
712 (setq quoted (eq (char-after) ?\"))
713 (goto-char (point-max))
714 (skip-chars-backward " \t")
715 (if (setq quoted (and quoted
716 (> (point) (1+ start))
717 (eq (char-before) ?\")))
718 (progn
719 (backward-char)
720 (setq start (1+ start)
721 end (point-marker)))
722 (setq end (point-marker)))
723 (goto-char start)
724 (while (search-forward "\"" end t)
725 (when (prog2
726 (backward-char)
727 (zerop (% (skip-chars-backward "\\\\") 2))
728 (goto-char (match-beginning 0)))
729 (insert "\\"))
730 (forward-char))
731 (when (and (not quoted)
732 (progn
733 (goto-char start)
734 (re-search-forward
735 (concat "[" ietf-drums-tspecials "]")
736 end t)))
737 (goto-char start)
738 (insert "\"")
739 (goto-char end)
740 (insert "\""))
741 (set-marker end nil)))
742 (goto-char (point-max)))
743 (when (and (mm-multibyte-p)
744 mail-parse-charset
745 (not (eq mail-parse-charset 'us-ascii))
746 (not (eq mail-parse-charset 'gnus-decoded)))
747 (mm-decode-coding-region b e mail-parse-charset))
748 (setq b (point)))
749 (when (and (mm-multibyte-p)
750 mail-parse-charset
751 (not (eq mail-parse-charset 'us-ascii))
752 (not (eq mail-parse-charset 'gnus-decoded)))
753 (mm-decode-coding-region b (point-max) mail-parse-charset))))))
754
755 (defun rfc2047-decode-string (string)
756 "Decode the quoted-printable-encoded STRING and return the results."
757 (let ((m (mm-multibyte-p)))
758 (if (string-match "=\\?" string)
759 (with-temp-buffer
760 ;; Fixme: This logic is wrong, but seems to be required by
761 ;; Gnus summary buffer generation. The value of `m' depends
762 ;; on the current buffer, not global multibyteness or that
763 ;; of the string. Also the string returned should always be
764 ;; multibyte in a multibyte session, i.e. the buffer should
765 ;; be multibyte before `buffer-string' is called.
766 (when m
767 (mm-enable-multibyte))
768 (insert string)
769 (inline
770 (rfc2047-decode-region (point-min) (point-max)))
771 (buffer-string))
772 ;; Fixme: As above, `m' here is inappropriate.
773 (if (and m
774 mail-parse-charset
775 (not (eq mail-parse-charset 'us-ascii))
776 (not (eq mail-parse-charset 'gnus-decoded)))
777 (mm-decode-coding-string string mail-parse-charset)
778 (mm-string-as-multibyte string)))))
779
780 (defun rfc2047-parse-and-decode (word)
781 "Decode WORD and return it if it is an encoded word.
782 Return WORD if it is not not an encoded word or if the charset isn't
783 decodable."
784 (if (not (string-match rfc2047-encoded-word-regexp word))
785 word
786 (or
787 (condition-case nil
788 (rfc2047-decode
789 (match-string 1 word)
790 (upcase (match-string 2 word))
791 (match-string 3 word))
792 (error word))
793 word))) ; un-decodable
794
795 (defun rfc2047-pad-base64 (string)
796 "Pad STRING to quartets."
797 ;; Be more liberal to accept buggy base64 strings. If
798 ;; base64-decode-string accepts buggy strings, this function could
799 ;; be aliased to identity.
800 (if (= 0 (mod (length string) 4))
801 string
802 (when (string-match "=+$" string)
803 (setq string (substring string 0 (match-beginning 0))))
804 (case (mod (length string) 4)
805 (0 string)
806 (1 string) ;; Error, don't pad it.
807 (2 (concat string "=="))
808 (3 (concat string "=")))))
809
810 (defun rfc2047-decode (charset encoding string)
811 "Decode STRING from the given MIME CHARSET in the given ENCODING.
812 Valid ENCODINGs are \"B\" and \"Q\".
813 If your Emacs implementation can't decode CHARSET, return nil."
814 (if (stringp charset)
815 (setq charset (intern (downcase charset))))
816 (if (or (not charset)
817 (eq 'gnus-all mail-parse-ignored-charsets)
818 (memq 'gnus-all mail-parse-ignored-charsets)
819 (memq charset mail-parse-ignored-charsets))
820 (setq charset mail-parse-charset))
821 (let ((cs (mm-charset-to-coding-system charset)))
822 (if (and (not cs) charset
823 (listp mail-parse-ignored-charsets)
824 (memq 'gnus-unknown mail-parse-ignored-charsets))
825 (setq cs (mm-charset-to-coding-system mail-parse-charset)))
826 (when cs
827 (when (and (eq cs 'ascii)
828 mail-parse-charset)
829 (setq cs mail-parse-charset))
830 (mm-decode-coding-string
831 (cond
832 ((equal "B" encoding)
833 (base64-decode-string
834 (rfc2047-pad-base64 string)))
835 ((equal "Q" encoding)
836 (quoted-printable-decode-string
837 (mm-replace-chars-in-string string ?_ ? )))
838 (t (error "Invalid encoding: %s" encoding)))
839 cs))))
840
841 (provide 'rfc2047)
842
843 ;;; arch-tag: a07fe3d4-22b5-4c4a-bd89-b1f82d5d36f6
844 ;;; rfc2047.el ends here