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