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