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