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