34683c3a64b7e4f47ef888f4515bde60dfd5f8b5
[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              (prog1
246                  (search-forward "=?" nil t)
247                (goto-char (point-min))))
248         (and charsets
249              (not (equal charsets (list (car message-posting-charset))))))))
250
251 ;; Use this syntax table when parsing into regions that may need
252 ;; encoding.  Double quotes are string delimiters, backslash is
253 ;; character quoting, and all other RFC 2822 special characters are
254 ;; treated as punctuation so we can use forward-sexp/forward-word to
255 ;; skip to the end of regions appropriately.  Nb. ietf-drums does
256 ;; things differently.
257 (defconst rfc2047-syntax-table
258   ;; (make-char-table 'syntax-table '(2)) only works in Emacs.
259   (let ((table (make-syntax-table)))
260     ;; The following is done to work for setting all elements of the table
261     ;; in Emacs 21 and 22 and XEmacs; it appears to be the cleanest way.
262     ;; Play safe and don't assume the form of the word syntax entry --
263     ;; copy it from ?a.
264     (if (fboundp 'set-char-table-range) ; Emacs
265         (funcall (intern "set-char-table-range")
266                  table t (aref (standard-syntax-table) ?a))
267       (if (fboundp 'put-char-table)
268           (if (fboundp 'get-char-table) ; warning avoidance
269               (put-char-table t (get-char-table ?a (standard-syntax-table))
270                               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     (modify-syntax-entry ?, "." table)
282     (modify-syntax-entry ?@ "." table)
283     table))
284
285 (defun rfc2047-encode-region (b e)
286   "Encode words in region B to E that need encoding.
287 By default, the region is treated as containing RFC2822 addresses.
288 Dynamically bind `rfc2047-encoding-type' to change that."
289   (save-restriction
290     (narrow-to-region b e)
291     (let ((encodable-regexp (if rfc2047-encode-encoded-words
292                                 "[^\000-\177]\\|=\\?"
293                               "[^\000-\177]"))
294           start                         ; start of current token
295           end                           ; end of current token
296           ;; Whether there's an encoded word before the current token,
297           ;; either immediately or separated by space.
298           last-encoded)
299       (if (eq 'mime rfc2047-encoding-type)
300           ;; Simple case.  Continuous words in which all those contain
301           ;; non-ASCII characters are encoded collectively.  Encoding
302           ;; ASCII words, including `Re:' used in Subject headers, is
303           ;; avoided for interoperability with non-MIME clients and
304           ;; for making it easy to find keywords.
305           (progn
306             (goto-char (point-min))
307             (while (progn (skip-chars-forward " \t\n")
308                           (not (eobp)))
309               (setq start (point))
310               (while (and (looking-at "[ \t\n]*\\([^ \t\n]+\\)")
311                           (progn
312                             (setq end (match-end 0))
313                             (re-search-forward encodable-regexp end t)))
314                 (goto-char end))
315               (if (> (point) start)
316                   (rfc2047-encode start (point))
317                 (goto-char end))))
318         ;; `address-mime' case -- take care of quoted words, comments.
319         (with-syntax-table rfc2047-syntax-table
320           (goto-char (point-min))
321           (condition-case nil           ; in case of unbalanced quotes
322               ;; Look for rfc2822-style: sequences of atoms, quoted
323               ;; strings, specials, whitespace.  (Specials mustn't be
324               ;; encoded.)
325               (while (not (eobp))
326                 ;; Skip whitespace.
327                 (skip-chars-forward " \t\n")
328                 (setq start (point))
329                 (cond
330                  ((not (char-after)))   ; eob
331                  ;; else token start
332                  ((eq ?\" (char-syntax (char-after)))
333                   ;; Quoted word.
334                   (forward-sexp)
335                   (setq end (point))
336                   ;; Does it need encoding?
337                   (goto-char start)
338                   (skip-chars-forward "\000-\177" end)
339                   (if (= end (point))
340                       (setq last-encoded  nil)
341                     ;; It needs encoding.  Strip the quotes first,
342                     ;; since encoded words can't occur in quotes.
343                     (goto-char end)
344                     (delete-backward-char 1)
345                     (goto-char start)
346                     (delete-char 1)
347                     (when last-encoded
348                       ;; There was a preceding quoted word.  We need
349                       ;; to include any separating whitespace in this
350                       ;; word to avoid it getting lost.
351                       (skip-chars-backward " \t")
352                       ;; A space is needed between the encoded words.
353                       (insert ? )
354                       (setq start (point)
355                             end (1+ end)))
356                     ;; Adjust the end position for the deleted quotes.
357                     (rfc2047-encode start (- end 2))
358                     (setq last-encoded t))) ; record that it was encoded
359                  ((eq ?. (char-syntax (char-after)))
360                   ;; Skip other delimiters, but record that they've
361                   ;; potentially separated quoted words.
362                   (forward-char)
363                   (setq last-encoded nil))
364                  (t                 ; normal token/whitespace sequence
365                   ;; Find the end.
366                   (skip-chars-backward " \t\n")
367                   (if (and (eq (char-before) ?\()
368                            ;; Look for the end of parentheses.
369                            (let ((string (buffer-substring (point)
370                                                            (point-max)))
371                                  (default-major-mode 'fundamental-mode))
372                              ;; Use `standard-syntax-table'.
373                              (with-temp-buffer
374                                (insert "(" string)
375                                (goto-char (point-min))
376                                (condition-case nil
377                                    (progn
378                                      (forward-list 1)
379                                      (setq end (- (point) 3)))
380                                  (error nil)))))
381                       ;; Encode text as an unstructured field.
382                       (let ((rfc2047-encoding-type 'mime))
383                         (rfc2047-encode-region start (+ (point) end))
384                         (forward-char))
385                     ;; Skip one ASCII word, or encode continuous words
386                     ;; in which all those contain non-ASCII characters.
387                     (skip-chars-forward " \t\n")
388                     (setq end nil)
389                     (while (not end)
390                       (when (looking-at "[\000-\177]+")
391                         (setq end (match-end 0))
392                         (if (re-search-forward "[ \t\n]\\|\\Sw" end t)
393                             (goto-char (match-beginning 0))
394                           (goto-char end)
395                           (setq end nil)))
396                       (unless end
397                         (setq end t)
398                         (when (looking-at "[^\000-\177]+")
399                           (goto-char (match-end 0))
400                           (while (and (looking-at "[ \t\n]+\\([^ \t\n]+\\)")
401                                       (setq end (match-end 0))
402                                       (string-match "[^\000-\177]"
403                                                     (match-string 1)))
404                             (goto-char end))
405                           (when (looking-at "[^ \t\n]+")
406                             (setq end (match-end 0))
407                             (if (re-search-forward "\\Sw+" end t)
408                                 ;; There are special characters better
409                                 ;; to be encoded so that MTAs may parse
410                                 ;; them safely.
411                                 (cond ((= end (point)))
412                                       ((looking-at "[^\000-\177]")
413                                        (setq end nil))
414                                       (t
415                                        (goto-char (1- (match-end 0)))
416                                        (unless (= (point) (match-beginning 0))
417                                          (insert " "))))
418                               (goto-char end)
419                               (skip-chars-forward " \t\n")
420                               (if (and (looking-at "[^ \t\n]+")
421                                        (string-match "[^\000-\177]"
422                                                      (match-string 0)))
423                                   (setq end nil)
424                                 (goto-char end)))))))
425                     (skip-chars-backward " \t\n")
426                     (setq end (point))
427                     (goto-char start)
428                     (skip-chars-forward "\000-\177" end)
429                     (if (= end (point))
430                         (setq last-encoded nil)
431                       (rfc2047-encode start end)
432                       (setq last-encoded t))))))
433             (error
434              (error "Invalid data for rfc2047 encoding: %s"
435                     (buffer-substring b e)))))))
436     (rfc2047-fold-region b (point))))
437
438 (defun rfc2047-encode-string (string)
439   "Encode words in STRING.
440 By default, the string is treated as containing addresses (see
441 `rfc2047-encoding-type')."
442   (with-temp-buffer
443     (insert string)
444     (rfc2047-encode-region (point-min) (point-max))
445     (buffer-string)))
446
447 (defun rfc2047-encode-1 (column string cs encoder start space &optional eword)
448   "Subroutine used by `rfc2047-encode'."
449   (cond ((string-equal string "")
450          (or eword ""))
451         ((>= column 76)
452          (when (and eword
453                     (string-match "\n[ \t]+\\'" eword))
454            ;; Reomove a superfluous empty line.
455            (setq eword (substring eword 0 (match-beginning 0))))
456          (rfc2047-encode-1 (length space) string cs encoder start " "
457                            (concat eword "\n" space)))
458         (t
459          (let ((index 0)
460                (limit (1- (length string)))
461                (prev "")
462                next)
463            (while (and prev
464                        (<= index limit))
465              (setq next (concat start
466                                 (funcall encoder
467                                          (if cs
468                                              (mm-encode-coding-string
469                                               (substring string 0 (1+ index))
470                                               cs)
471                                            (substring string 0 (1+ index))))
472                                 "?="))
473              (if (<= (+ column (length next)) 76)
474                  (setq prev next
475                        index (1+ index))
476                (setq next prev
477                      prev nil)))
478            (setq eword (concat eword next))
479            (if (> index limit)
480                eword
481              (when (string-match "\n[ \t]+\\'" eword)
482                ;; Reomove a superfluous empty line.
483                (setq eword (substring eword 0 (match-beginning 0))))
484              (rfc2047-encode-1 (length space) (substring string index)
485                                cs encoder start " "
486                                (concat eword "\n" space)))))))
487
488 (defun rfc2047-encode (b e)
489   "Encode the word(s) in the region B to E.
490 By default, the region is treated as containing addresses (see
491 `rfc2047-encoding-type')."
492   (let ((mime-charset (or (mm-find-mime-charset-region b e) (list 'us-ascii)))
493         cs encoding space eword)
494     (cond ((> (length mime-charset) 1)
495            (error "Can't rfc2047-encode `%s'"
496                   (buffer-substring-no-properties b e)))
497           ((= (length mime-charset) 1)
498            (setq mime-charset (car mime-charset)
499                  cs (mm-charset-to-coding-system mime-charset))
500            (unless (and (mm-multibyte-p)
501                         (mm-coding-system-p cs))
502              (setq cs nil))
503            (save-restriction
504              (narrow-to-region b e)
505              (setq encoding
506                    (or (cdr (assq mime-charset
507                                   rfc2047-charset-encoding-alist))
508                        ;; For the charsets that don't have a preferred
509                        ;; encoding, choose the one that's shorter.
510                        (if (eq (rfc2047-qp-or-base64) 'base64)
511                            'B
512                          'Q)))
513              (widen)
514              (goto-char b)
515              (unless (= 0 (skip-chars-backward " \t"))
516                (setq space (buffer-substring-no-properties (point) b)))
517              (setq eword (rfc2047-encode-1
518                           (- b (point-at-bol))
519                           (mm-replace-in-string
520                            (buffer-substring-no-properties b e)
521                            "\n\\([ \t]?\\)" "\\1")
522                           cs
523                           (or (cdr (assq encoding
524                                          rfc2047-encode-function-alist))
525                               'identity)
526                           (concat "=?" (downcase (symbol-name mime-charset))
527                                   "?" (upcase (symbol-name encoding)) "?")
528                           (or space " ")))
529              (delete-region (if (eq (aref eword 0) ?\n)
530                                 (point)
531                               (goto-char b))
532                             e)
533              (insert eword)
534              (unless (or (eolp)
535                          (looking-at "[ \t\n)]"))
536                (insert " "))))
537           (t
538            (goto-char e)))))
539
540 (defun rfc2047-fold-field ()
541   "Fold the current header field."
542   (save-excursion
543     (save-restriction
544       (rfc2047-narrow-to-field)
545       (rfc2047-fold-region (point-min) (point-max)))))
546
547 (defun rfc2047-fold-region (b e)
548   "Fold long lines in region B to E."
549   (save-restriction
550     (narrow-to-region b e)
551     (goto-char (point-min))
552     (let ((break nil)
553           (qword-break nil)
554           (first t)
555           (bol (save-restriction
556                  (widen)
557                  (point-at-bol))))
558       (while (not (eobp))
559         (when (and (or break qword-break)
560                    (> (- (point) bol) 76))
561           (goto-char (or break qword-break))
562           (setq break nil
563                 qword-break nil)
564           (skip-chars-backward " \t")
565           (if (looking-at "[ \t]")
566               (insert ?\n)
567             (insert "\n "))
568           (setq bol (1- (point)))
569           ;; Don't break before the first non-LWSP characters.
570           (skip-chars-forward " \t")
571           (unless (eobp)
572             (forward-char 1)))
573         (cond
574          ((eq (char-after) ?\n)
575           (forward-char 1)
576           (setq bol (point)
577                 break nil
578                 qword-break nil)
579           (skip-chars-forward " \t")
580           (unless (or (eobp) (eq (char-after) ?\n))
581             (forward-char 1)))
582          ((eq (char-after) ?\r)
583           (forward-char 1))
584          ((memq (char-after) '(?  ?\t))
585           (skip-chars-forward " \t")
586           (unless first ;; Don't break just after the header name.
587             (setq break (point))))
588          ((not break)
589           (if (not (looking-at "=\\?[^=]"))
590               (if (eq (char-after) ?=)
591                   (forward-char 1)
592                 (skip-chars-forward "^ \t\n\r="))
593             ;; Don't break at the start of the field.
594             (unless (= (point) b)
595               (setq qword-break (point)))
596             (skip-chars-forward "^ \t\n\r")))
597          (t
598           (skip-chars-forward "^ \t\n\r")))
599         (setq first nil))
600       (when (and (or break qword-break)
601                  (> (- (point) bol) 76))
602         (goto-char (or break qword-break))
603         (setq break nil
604               qword-break nil)
605           (if (looking-at "[ \t]")
606               (insert ?\n)
607             (insert "\n "))
608         (setq bol (1- (point)))
609         ;; Don't break before the first non-LWSP characters.
610         (skip-chars-forward " \t")
611         (unless (eobp)
612           (forward-char 1))))))
613
614 (defun rfc2047-unfold-field ()
615   "Fold the current line."
616   (save-excursion
617     (save-restriction
618       (rfc2047-narrow-to-field)
619       (rfc2047-unfold-region (point-min) (point-max)))))
620
621 (defun rfc2047-unfold-region (b e)
622   "Unfold lines in region B to E."
623   (save-restriction
624     (narrow-to-region b e)
625     (goto-char (point-min))
626     (let ((bol (save-restriction
627                  (widen)
628                  (point-at-bol)))
629           (eol (point-at-eol)))
630       (forward-line 1)
631       (while (not (eobp))
632         (if (and (looking-at "[ \t]")
633                  (< (- (point-at-eol) bol) 76))
634             (delete-region eol (progn
635                                  (goto-char eol)
636                                  (skip-chars-forward "\r\n")
637                                  (point)))
638           (setq bol (point-at-bol)))
639         (setq eol (point-at-eol))
640         (forward-line 1)))))
641
642 (defun rfc2047-b-encode-string (string)
643   "Base64-encode the header contained in STRING."
644   (base64-encode-string string t))
645
646 (defun rfc2047-q-encode-string (string)
647   "Quoted-printable-encode the header in STRING."
648   (mm-with-unibyte-buffer
649     (insert string)
650     (quoted-printable-encode-region
651      (point-min) (point-max) nil
652      ;; = (\075), _ (\137), ? (\077) are used in the encoded word.
653      ;; Avoid using 8bit characters.
654      ;; This list excludes `especials' (see the RFC2047 syntax),
655      ;; meaning that some characters in non-structured fields will
656      ;; get encoded when they con't need to be.  The following is
657      ;; what it used to be.
658      ;;;  ;; Equivalent to "^\000-\007\011\013\015-\037\200-\377=_?"
659      ;;;  "\010\012\014\040-\074\076\100-\136\140-\177")
660      "-\b\n\f !#-'*+0-9A-Z\\^`-~\d")
661     (subst-char-in-region (point-min) (point-max) ?  ?_)
662     (buffer-string)))
663
664 ;;;
665 ;;; Functions for decoding RFC2047 messages
666 ;;;
667
668 (eval-and-compile
669   (defconst rfc2047-encoded-word-regexp
670     "=\\?\\([^][\000-\040()<>@,\;:*\\\"/?.=]+\\)\\(?:\\*[^?]+\\)?\
671 \\?\\(B\\|Q\\)\\?\\([!->@-~ ]*\\)\\?="))
672
673 ;; Fixme: This should decode in place, not cons intermediate strings.
674 ;; Also check whether it needs to worry about delimiting fields like
675 ;; encoding.
676
677 ;; In fact it's reported that (invalid) encoding of mailboxes in
678 ;; addr-specs is in use, so delimiting fields might help.  Probably
679 ;; not decoding a word which isn't properly delimited is good enough
680 ;; and worthwhile (is it more correct or not?), e.g. something like
681 ;; `=?iso-8859-1?q?foo?=@'.
682
683 (defun rfc2047-decode-region (start end)
684   "Decode MIME-encoded words in region between START and END."
685   (interactive "r")
686   (let ((case-fold-search t)
687         b e)
688     (save-excursion
689       (save-restriction
690         (narrow-to-region start end)
691         (goto-char (point-min))
692         ;; Remove whitespace between encoded words.
693         (while (re-search-forward
694                 (eval-when-compile
695                   (concat "\\(" rfc2047-encoded-word-regexp "\\)"
696                           "\\(\n?[ \t]\\)+"
697                           "\\(" rfc2047-encoded-word-regexp "\\)"))
698                 nil t)
699           (delete-region (goto-char (match-end 1)) (match-beginning 6)))
700         ;; Decode the encoded words.
701         (setq b (goto-char (point-min)))
702         (while (re-search-forward rfc2047-encoded-word-regexp nil t)
703           (setq e (match-beginning 0))
704           (insert (rfc2047-parse-and-decode
705                    (prog1
706                        (match-string 0)
707                      (delete-region (match-beginning 0) (match-end 0)))))
708           ;; Remove newlines between decoded words, though such things
709           ;; essentially must not be there.
710           (save-restriction
711             (narrow-to-region e (point))
712             (goto-char e)
713             (while (re-search-forward "[\n\r]+" nil t)
714               (replace-match " "))
715             (goto-char (point-max)))
716           (when (and (mm-multibyte-p)
717                      mail-parse-charset
718                      (not (eq mail-parse-charset 'us-ascii))
719                      (not (eq mail-parse-charset 'gnus-decoded)))
720             (mm-decode-coding-region b e mail-parse-charset))
721           (setq b (point)))
722         (when (and (mm-multibyte-p)
723                    mail-parse-charset
724                    (not (eq mail-parse-charset 'us-ascii))
725                    (not (eq mail-parse-charset 'gnus-decoded)))
726           (mm-decode-coding-region b (point-max) mail-parse-charset))))))
727
728 (defun rfc2047-decode-string (string)
729   "Decode the quoted-printable-encoded STRING and return the results."
730   (let ((m (mm-multibyte-p)))
731     (if (string-match "=\\?" string)
732         (with-temp-buffer
733           ;; Fixme: This logic is wrong, but seems to be required by
734           ;; Gnus summary buffer generation.  The value of `m' depends
735           ;; on the current buffer, not global multibyteness or that
736           ;; of the string.  Also the string returned should always be
737           ;; multibyte in a multibyte session, i.e. the buffer should
738           ;; be multibyte before `buffer-string' is called.
739           (when m
740             (mm-enable-multibyte))
741           (insert string)
742           (inline
743             (rfc2047-decode-region (point-min) (point-max)))
744           (buffer-string))
745       ;; Fixme: As above, `m' here is inappropriate.
746       (if (and m
747                mail-parse-charset
748                (not (eq mail-parse-charset 'us-ascii))
749                (not (eq mail-parse-charset 'gnus-decoded)))
750           ;; `decode-coding-string' in Emacs offers a third optional
751           ;; arg NOCOPY to avoid consing a new string if the decoding
752           ;; is "trivial".  Unfortunately it currently doesn't
753           ;; consider anything else than a `nil' coding system
754           ;; trivial.
755           ;; `rfc2047-decode-string' is called multiple times for each
756           ;; article during summary buffer generation, and we really
757           ;; want to avoid unnecessary consing.  So we bypass
758           ;; `decode-coding-string' if the string is purely ASCII.
759           (if (and (fboundp 'detect-coding-string)
760                    ;; string is purely ASCII
761                    (eq (detect-coding-string string t) 'undecided))
762               string
763             (mm-decode-coding-string string mail-parse-charset))
764         (mm-string-as-multibyte string)))))
765
766 (defun rfc2047-parse-and-decode (word)
767   "Decode WORD and return it if it is an encoded word.
768 Return WORD if it is not not an encoded word or if the charset isn't
769 decodable."
770   (if (not (string-match rfc2047-encoded-word-regexp word))
771       word
772     (or
773      (condition-case nil
774          (rfc2047-decode
775           (match-string 1 word)
776           (string-to-char (match-string 2 word))
777           (match-string 3 word))
778        (error word))
779      word)))                            ; un-decodable
780
781 (defun rfc2047-pad-base64 (string)
782   "Pad STRING to quartets."
783   ;; Be more liberal to accept buggy base64 strings. If
784   ;; base64-decode-string accepts buggy strings, this function could
785   ;; be aliased to identity.
786   (if (= 0 (mod (length string) 4))
787       string
788     (when (string-match "=+$" string)
789       (setq string (substring string 0 (match-beginning 0))))
790     (case (mod (length string) 4)
791       (0 string)
792       (1 string) ;; Error, don't pad it.
793       (2 (concat string "=="))
794       (3 (concat string "=")))))
795
796 (defun rfc2047-decode (charset encoding string)
797   "Decode STRING from the given MIME CHARSET in the given ENCODING.
798 Valid ENCODINGs are the characters \"B\" and \"Q\".
799 If your Emacs implementation can't decode CHARSET, return nil."
800   (if (stringp charset)
801       (setq charset (intern (downcase charset))))
802   (if (or (not charset)
803           (eq 'gnus-all mail-parse-ignored-charsets)
804           (memq 'gnus-all mail-parse-ignored-charsets)
805           (memq charset mail-parse-ignored-charsets))
806       (setq charset mail-parse-charset))
807   (let ((cs (mm-charset-to-coding-system charset)))
808     (if (and (not cs) charset
809              (listp mail-parse-ignored-charsets)
810              (memq 'gnus-unknown mail-parse-ignored-charsets))
811         (setq cs (mm-charset-to-coding-system mail-parse-charset)))
812     (when cs
813       (when (and (eq cs 'ascii)
814                  mail-parse-charset)
815         (setq cs mail-parse-charset))
816       (mm-decode-coding-string
817        (cond
818         ((char-equal ?B encoding)
819          (base64-decode-string
820           (rfc2047-pad-base64 string)))
821         ((char-equal ?Q encoding)
822          (quoted-printable-decode-string
823           (mm-subst-char-in-string ?_ ? string t)))
824         (t (error "Invalid encoding: %c" encoding)))
825        cs))))
826
827 (provide 'rfc2047)
828
829 ;;; arch-tag: a07fe3d4-22b5-4c4a-bd89-b1f82d5d36f6
830 ;;; rfc2047.el ends here