6de49eb6cefaa8dc2c523145b84402ae3c47eac6
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010-2011 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;         Simon Josefsson <simon@josefsson.org>
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; nnimap interfaces Gnus with IMAP servers.
26
27 ;;; Code:
28
29 ;; For Emacs <22.2 and XEmacs.
30 (eval-and-compile
31   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
32
33 (eval-and-compile
34   (require 'nnheader))
35
36 (eval-when-compile
37   (require 'cl))
38
39 (require 'nnheader)
40 (require 'gnus-util)
41 (require 'gnus)
42 (require 'nnoo)
43 (require 'netrc)
44 (require 'utf7)
45 (require 'tls)
46 (require 'parse-time)
47 (require 'nnmail)
48 (require 'proto-stream)
49
50 (autoload 'auth-source-forget-user-or-password "auth-source")
51 (autoload 'auth-source-user-or-password "auth-source")
52
53 (nnoo-declare nnimap)
54
55 (defvoo nnimap-address nil
56   "The address of the IMAP server.")
57
58 (defvoo nnimap-server-port nil
59   "The IMAP port used.
60 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
61 it will default to `imap'.")
62
63 (defvoo nnimap-stream 'undecided
64   "How nnimap will talk to the IMAP server.
65 Values are `ssl', `network', `starttls' or `shell'.
66 The default is to try `ssl' first, and then `network'.")
67
68 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
69                                  (if (listp imap-shell-program)
70                                      (car imap-shell-program)
71                                    imap-shell-program)
72                                "ssh %s imapd"))
73
74 (defvoo nnimap-inbox nil
75   "The mail box where incoming mail arrives and should be split out of.")
76
77 (defvoo nnimap-split-methods nil
78   "How mail is split.
79 Uses the same syntax as nnmail-split-methods")
80
81 (defvoo nnimap-split-fancy nil
82   "Uses the same syntax as nnmail-split-fancy.")
83
84 (defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
85   "Articles with the flags in the list will not be considered when splitting.")
86
87 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
88                         "Emacs 24.1")
89
90 (defvoo nnimap-authenticator nil
91   "How nnimap authenticate itself to the server.
92 Possible choices are nil (use default methods) or `anonymous'.")
93
94 (defvoo nnimap-expunge t
95   "If non-nil, expunge articles after deleting them.
96 This is always done if the server supports UID EXPUNGE, but it's
97 not done by default on servers that doesn't support that command.")
98
99 (defvoo nnimap-streaming t
100   "If non-nil, try to use streaming commands with IMAP servers.
101 Switching this off will make nnimap slower, but it helps with
102 some servers.")
103
104 (defvoo nnimap-connection-alist nil)
105
106 (defvoo nnimap-current-infos nil)
107
108 (defvoo nnimap-fetch-partial-articles nil
109   "If non-nil, Gnus will fetch partial articles.
110 If t, nnimap will fetch only the first part.  If a string, it
111 will fetch all parts that have types that match that string.  A
112 likely value would be \"text/\" to automatically fetch all
113 textual parts.")
114
115 (defvar nnimap-process nil)
116
117 (defvar nnimap-status-string "")
118
119 (defvar nnimap-split-download-body-default nil
120   "Internal variable with default value for `nnimap-split-download-body'.")
121
122 (defvar nnimap-keepalive-timer nil)
123 (defvar nnimap-process-buffers nil)
124
125 (defstruct nnimap
126   group process commands capabilities select-result newlinep server
127   last-command-time greeting examined stream-type)
128
129 (defvar nnimap-object nil)
130
131 (defvar nnimap-mark-alist
132   '((read "\\Seen" %Seen)
133     (tick "\\Flagged" %Flagged)
134     (reply "\\Answered" %Answered)
135     (expire "gnus-expire")
136     (dormant "gnus-dormant")
137     (score "gnus-score")
138     (save "gnus-save")
139     (download "gnus-download")
140     (forward "gnus-forward")))
141
142 (defvar nnimap-quirks
143   '(("QRESYNC" "Zimbra" "QRESYNC ")))
144
145 (defun nnimap-buffer ()
146   (nnimap-find-process-buffer nntp-server-buffer))
147
148 (defun nnimap-header-parameters ()
149   (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
150           (format
151            (if (nnimap-ver4-p)
152                "BODY.PEEK[HEADER.FIELDS %s]"
153              "RFC822.HEADER.LINES %s")
154            (append '(Subject From Date Message-Id
155                              References In-Reply-To Xref)
156                    nnmail-extra-headers))))
157
158 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
159   (with-current-buffer nntp-server-buffer
160     (erase-buffer)
161     (when (nnimap-possibly-change-group group server)
162       (with-current-buffer (nnimap-buffer)
163         (erase-buffer)
164         (nnimap-wait-for-response
165          (nnimap-send-command
166           "UID FETCH %s %s"
167           (nnimap-article-ranges (gnus-compress-sequence articles))
168           (nnimap-header-parameters))
169          t)
170         (nnimap-transform-headers)
171         (nnheader-remove-cr-followed-by-lf))
172       (insert-buffer-substring
173        (nnimap-find-process-buffer (current-buffer))))
174     'headers))
175
176 (defun nnimap-transform-headers ()
177   (goto-char (point-min))
178   (let (article bytes lines size string)
179     (block nil
180       (while (not (eobp))
181         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
182           (delete-region (point) (progn (forward-line 1) (point)))
183           (when (eobp)
184             (return)))
185         (setq article (match-string 1))
186         ;; Unfold quoted {number} strings.
187         (while (re-search-forward "[^]][ (]{\\([0-9]+\\)}\r?\n"
188                                   (1+ (line-end-position)) t)
189           (setq size (string-to-number (match-string 1)))
190           (delete-region (+ (match-beginning 0) 2) (point))
191           (setq string (buffer-substring (point) (+ (point) size)))
192           (delete-region (point) (+ (point) size))
193           (insert (format "%S" string)))
194         (setq bytes (nnimap-get-length)
195               lines nil)
196         (beginning-of-line)
197         (setq size
198               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
199                                       (line-end-position)
200                                       t)
201                    (match-string 1)))
202         (beginning-of-line)
203         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
204           (let ((structure (ignore-errors
205                              (read (current-buffer)))))
206             (while (and (consp structure)
207                         (not (stringp (car structure))))
208               (setq structure (car structure)))
209             (setq lines (nth 7 structure))))
210         (delete-region (line-beginning-position) (line-end-position))
211         (insert (format "211 %s Article retrieved." article))
212         (forward-line 1)
213         (when size
214           (insert (format "Chars: %s\n" size)))
215         (when lines
216           (insert (format "Lines: %s\n" lines)))
217         (unless (re-search-forward "^\r$" nil t)
218           (goto-char (point-max)))
219         (delete-region (line-beginning-position) (line-end-position))
220         (insert ".")
221         (forward-line 1)))))
222
223 (defun nnimap-unfold-quoted-lines ()
224   ;; Unfold quoted {number} strings.
225   (let (size string)
226     (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
227       (setq size (string-to-number (match-string 1)))
228       (delete-region (1+ (match-beginning 0)) (point))
229       (setq string (buffer-substring (point) (+ (point) size)))
230       (delete-region (point) (+ (point) size))
231       (insert (format "%S" string)))))
232
233 (defun nnimap-get-length ()
234   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
235        (string-to-number (match-string 1))))
236
237 (defun nnimap-article-ranges (ranges)
238   (let (result)
239     (cond
240      ((numberp ranges)
241       (number-to-string ranges))
242      ((numberp (cdr ranges))
243       (format "%d:%d" (car ranges) (cdr ranges)))
244      (t
245       (dolist (elem ranges)
246         (push
247          (if (consp elem)
248              (format "%d:%d" (car elem) (cdr elem))
249            (number-to-string elem))
250          result))
251       (mapconcat #'identity (nreverse result) ",")))))
252
253 (deffoo nnimap-open-server (server &optional defs)
254   (if (nnimap-server-opened server)
255       t
256     (unless (assq 'nnimap-address defs)
257       (setq defs (append defs (list (list 'nnimap-address server)))))
258     (nnoo-change-server 'nnimap server defs)
259     (or (nnimap-find-connection nntp-server-buffer)
260         (nnimap-open-connection nntp-server-buffer))))
261
262 (defun nnimap-make-process-buffer (buffer)
263   (with-current-buffer
264       (generate-new-buffer (format "*nnimap %s %s %s*"
265                                    nnimap-address nnimap-server-port
266                                    (gnus-buffer-exists-p buffer)))
267     (mm-disable-multibyte)
268     (buffer-disable-undo)
269     (gnus-add-buffer)
270     (set (make-local-variable 'after-change-functions) nil)
271     (set (make-local-variable 'nnimap-object)
272          (make-nnimap :server (nnoo-current-server 'nnimap)))
273     (push (list buffer (current-buffer)) nnimap-connection-alist)
274     (push (current-buffer) nnimap-process-buffers)
275     (current-buffer)))
276
277 (defun nnimap-credentials (address ports &optional inhibit-create)
278   (let (port credentials)
279     ;; Request the credentials from all ports, but only query on the
280     ;; last port if all the previous ones have failed.
281     (while (and (null credentials)
282                 (setq port (pop ports)))
283       (setq credentials
284             (auth-source-user-or-password
285              '("login" "password") address port nil
286              (if inhibit-create
287                  nil
288                (null ports)))))
289     credentials))
290
291 (defun nnimap-keepalive ()
292   (let ((now (current-time)))
293     (dolist (buffer nnimap-process-buffers)
294       (when (buffer-name buffer)
295         (with-current-buffer buffer
296           (when (and nnimap-object
297                      (nnimap-last-command-time nnimap-object)
298                      (> (gnus-float-time
299                          (time-subtract
300                           now
301                           (nnimap-last-command-time nnimap-object)))
302                         ;; More than five minutes since the last command.
303                         (* 5 60)))
304             (nnimap-send-command "NOOP")))))))
305
306 (defun nnimap-open-connection (buffer)
307   ;; Be backwards-compatible -- the earlier value of nnimap-stream was
308   ;; `ssl' when nnimap-server-port was nil.  Sort of.
309   (when (and nnimap-server-port
310              (eq nnimap-stream 'undecided))
311     (setq nnimap-stream 'ssl))
312   (let ((stream
313          (if (eq nnimap-stream 'undecided)
314              (loop for type in '(ssl network)
315                    for stream = (let ((nnimap-stream type))
316                                   (nnimap-open-connection-1 buffer))
317                    while (eq stream 'no-connect)
318                    finally (return stream))
319            (nnimap-open-connection-1 buffer))))
320     (if (eq stream 'no-connect)
321         nil
322       stream)))
323
324 (defun nnimap-open-connection-1 (buffer)
325   (unless nnimap-keepalive-timer
326     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
327                                               'nnimap-keepalive)))
328   (with-current-buffer (nnimap-make-process-buffer buffer)
329     (let* ((coding-system-for-read 'binary)
330            (coding-system-for-write 'binary)
331            (port nil)
332            (ports
333             (cond
334              ((or (eq nnimap-stream 'network)
335                   (eq nnimap-stream 'starttls))
336               (nnheader-message 7 "Opening connection to %s..."
337                                 nnimap-address)
338               '("143" "imap"))
339              ((eq nnimap-stream 'shell)
340               (nnheader-message 7 "Opening connection to %s via shell..."
341                                 nnimap-address)
342               '("imap"))
343              ((memq nnimap-stream '(ssl tls))
344               (nnheader-message 7 "Opening connection to %s via tls..."
345                                 nnimap-address)
346               '("143" "993" "imap" "imaps"))
347              (t
348               (error "Unknown stream type: %s" nnimap-stream))))
349            (proto-stream-always-use-starttls t)
350            login-result credentials)
351       (when nnimap-server-port
352         (setq ports (append ports (list nnimap-server-port))))
353       (destructuring-bind (stream greeting capabilities stream-type)
354           (open-protocol-stream
355            "*nnimap*" (current-buffer) nnimap-address (car (last ports))
356            :type nnimap-stream
357            :shell-command nnimap-shell-program
358            :capability-command "1 CAPABILITY\r\n"
359            :success " OK "
360            :starttls-function
361            (lambda (capabilities)
362              (when (gnus-string-match-p "STARTTLS" capabilities)
363                "1 STARTTLS\r\n")))
364         (setf (nnimap-process nnimap-object) stream)
365         (setf (nnimap-stream-type nnimap-object) stream-type)
366         (if (not stream)
367             (progn
368               (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
369                                nnimap-address port nnimap-stream)
370               'no-connect)
371           (gnus-set-process-query-on-exit-flag stream nil)
372           (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
373               (nnheader-report 'nnimap "%s" greeting)
374             ;; Store the greeting (for debugging purposes).
375             (setf (nnimap-greeting nnimap-object) greeting)
376             (setf (nnimap-capabilities nnimap-object)
377                   (mapcar #'upcase
378                           (split-string capabilities)))
379             (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
380               (if (not (setq credentials
381                              (if (eq nnimap-authenticator 'anonymous)
382                                  (list "anonymous"
383                                        (message-make-address))
384                                (or
385                                 ;; First look for the credentials based
386                                 ;; on the virtual server name.
387                                 (nnimap-credentials
388                                  (nnoo-current-server 'nnimap) ports t)
389                                 ;; Then look them up based on the
390                                 ;; physical address.
391                                 (nnimap-credentials nnimap-address ports)))))
392                   (setq nnimap-object nil)
393                 (setq login-result
394                       (nnimap-login (car credentials) (cadr credentials)))
395                 (unless (car login-result)
396                   ;; If the login failed, then forget the credentials
397                   ;; that are now possibly cached.
398                   (dolist (host (list (nnoo-current-server 'nnimap)
399                                       nnimap-address))
400                     (dolist (port ports)
401                       (dolist (element '("login" "password"))
402                         (auth-source-forget-user-or-password
403                          element host port))))
404                   (delete-process (nnimap-process nnimap-object))
405                   (setq nnimap-object nil))))
406             (when nnimap-object
407               (when (nnimap-capability "QRESYNC")
408                 (nnimap-command "ENABLE QRESYNC"))
409               (nnimap-process nnimap-object))))))))
410
411 (autoload 'rfc2104-hash "rfc2104")
412
413 (defun nnimap-login (user password)
414   (cond
415    ;; Prefer plain LOGIN if it's enabled (since it requires fewer
416    ;; round trips than CRAM-MD5, and it's less likely to be buggy),
417    ;; and we're using an encrypted connection.
418    ((and (not (nnimap-capability "LOGINDISABLED"))
419          (eq (nnimap-stream-type nnimap-object) 'tls))
420     (nnimap-command "LOGIN %S %S" user password))
421    ((nnimap-capability "AUTH=CRAM-MD5")
422     (erase-buffer)
423     (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
424           (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
425       (process-send-string
426        (get-buffer-process (current-buffer))
427        (concat
428         (base64-encode-string
429          (concat user " "
430                  (rfc2104-hash 'md5 64 16 password
431                                (base64-decode-string challenge))))
432         "\r\n"))
433       (nnimap-wait-for-response sequence)))
434    ((not (nnimap-capability "LOGINDISABLED"))
435     (nnimap-command "LOGIN %S %S" user password))
436    ((nnimap-capability "AUTH=PLAIN")
437     (nnimap-command
438      "AUTHENTICATE PLAIN %s"
439      (base64-encode-string
440       (format "\000%s\000%s"
441               (nnimap-quote-specials user)
442               (nnimap-quote-specials password)))))))
443
444 (defun nnimap-quote-specials (string)
445   (with-temp-buffer
446     (insert string)
447     (goto-char (point-min))
448     (while (re-search-forward "[\\\"]" nil t)
449       (forward-char -1)
450       (insert "\\")
451       (forward-char 1))
452     (buffer-string)))
453
454 (defun nnimap-find-parameter (parameter elems)
455   (let (result)
456     (dolist (elem elems)
457       (cond
458        ((equal (car elem) parameter)
459         (setq result (cdr elem)))
460        ((and (equal (car elem) "OK")
461              (consp (cadr elem))
462              (equal (caadr elem) parameter))
463         (setq result (cdr (cadr elem))))))
464     result))
465
466 (deffoo nnimap-close-server (&optional server)
467   (when (nnoo-change-server 'nnimap server nil)
468     (ignore-errors
469       (delete-process (get-buffer-process (nnimap-buffer))))
470     (nnoo-close-server 'nnimap server)
471     t))
472
473 (deffoo nnimap-request-close ()
474   t)
475
476 (deffoo nnimap-server-opened (&optional server)
477   (and (nnoo-current-server-p 'nnimap server)
478        nntp-server-buffer
479        (gnus-buffer-live-p nntp-server-buffer)
480        (nnimap-find-connection nntp-server-buffer)))
481
482 (deffoo nnimap-status-message (&optional server)
483   nnimap-status-string)
484
485 (deffoo nnimap-request-article (article &optional group server to-buffer)
486   (with-current-buffer nntp-server-buffer
487     (let ((result (nnimap-possibly-change-group group server))
488           parts structure)
489       (when (stringp article)
490         (setq article (nnimap-find-article-by-message-id group article)))
491       (when (and result
492                  article)
493         (erase-buffer)
494         (with-current-buffer (nnimap-buffer)
495           (erase-buffer)
496           (when nnimap-fetch-partial-articles
497             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
498             (goto-char (point-min))
499             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
500               (setq structure (ignore-errors
501                                 (let ((start (point)))
502                                   (forward-sexp 1)
503                                   (downcase-region start (point))
504                                   (goto-char start)
505                                   (read (current-buffer))))
506                     parts (nnimap-find-wanted-parts structure))))
507           (when (if parts
508                     (nnimap-get-partial-article article parts structure)
509                   (nnimap-get-whole-article article))
510             (let ((buffer (current-buffer)))
511               (with-current-buffer (or to-buffer nntp-server-buffer)
512                 (erase-buffer)
513                 (insert-buffer-substring buffer)
514                 (nnheader-ms-strip-cr)
515                 (cons group article)))))))))
516
517 (deffoo nnimap-request-head (article &optional group server to-buffer)
518   (when (nnimap-possibly-change-group group server)
519     (with-current-buffer (nnimap-buffer)
520       (when (stringp article)
521         (setq article (nnimap-find-article-by-message-id group article)))
522       (if (null article)
523           nil
524         (nnimap-get-whole-article
525          article (format "UID FETCH %%d %s"
526                          (nnimap-header-parameters)))
527         (let ((buffer (current-buffer)))
528           (with-current-buffer (or to-buffer nntp-server-buffer)
529             (erase-buffer)
530             (insert-buffer-substring buffer)
531             (nnheader-ms-strip-cr)
532             (cons group article)))))))
533
534 (defun nnimap-get-whole-article (article &optional command)
535   (let ((result
536          (nnimap-command
537           (or command
538               (if (nnimap-ver4-p)
539                   "UID FETCH %d BODY.PEEK[]"
540                 "UID FETCH %d RFC822.PEEK"))
541           article)))
542     ;; Check that we really got an article.
543     (goto-char (point-min))
544     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
545       (setq result nil))
546     (when result
547       ;; Remove any data that may have arrived before the FETCH data.
548       (beginning-of-line)
549       (unless (bobp)
550         (delete-region (point-min) (point)))
551       (let ((bytes (nnimap-get-length)))
552         (delete-region (line-beginning-position)
553                        (progn (forward-line 1) (point)))
554         (goto-char (+ (point) bytes))
555         (delete-region (point) (point-max)))
556       t)))
557
558 (defun nnimap-capability (capability)
559   (member capability (nnimap-capabilities nnimap-object)))
560
561 (defun nnimap-ver4-p ()
562   (nnimap-capability "IMAP4REV1"))
563
564 (defun nnimap-get-partial-article (article parts structure)
565   (let ((result
566          (nnimap-command
567           "UID FETCH %d (%s %s)"
568           article
569           (if (nnimap-ver4-p)
570               "BODY.PEEK[HEADER]"
571             "RFC822.HEADER")
572           (if (nnimap-ver4-p)
573               (mapconcat (lambda (part)
574                            (format "BODY.PEEK[%s]" part))
575                          parts " ")
576             (mapconcat (lambda (part)
577                          (format "RFC822.PEEK[%s]" part))
578                        parts " ")))))
579     (when result
580       (nnimap-convert-partial-article structure))))
581
582 (defun nnimap-convert-partial-article (structure)
583   ;; First just skip past the headers.
584   (goto-char (point-min))
585   (let ((bytes (nnimap-get-length))
586         id parts)
587     ;; Delete "FETCH" line.
588     (delete-region (line-beginning-position)
589                    (progn (forward-line 1) (point)))
590     (goto-char (+ (point) bytes))
591     ;; Collect all the body parts.
592     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
593       (setq id (match-string 1)
594             bytes (or (nnimap-get-length) 0))
595       (beginning-of-line)
596       (delete-region (point) (progn (forward-line 1) (point)))
597       (push (list id (buffer-substring (point) (+ (point) bytes)))
598             parts)
599       (delete-region (point) (+ (point) bytes)))
600     ;; Delete trailing junk.
601     (delete-region (point) (point-max))
602     ;; Now insert all the parts again where they fit in the structure.
603     (nnimap-insert-partial-structure structure parts)
604     t))
605
606 (defun nnimap-insert-partial-structure (structure parts &optional subp)
607   (let (type boundary)
608     (let ((bstruc structure))
609       (while (consp (car bstruc))
610         (pop bstruc))
611       (setq type (car bstruc))
612       (setq bstruc (car (cdr bstruc)))
613       (let ((has-boundary (member "boundary" bstruc)))
614         (when has-boundary
615           (setq boundary (cadr has-boundary)))))
616     (when subp
617       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
618                       (downcase type) boundary)))
619     (while (not (stringp (car structure)))
620       (insert "\n--" boundary "\n")
621       (if (consp (caar structure))
622           (nnimap-insert-partial-structure (pop structure) parts t)
623         (let ((bit (pop structure)))
624           (insert (format  "Content-type: %s/%s"
625                            (downcase (nth 0 bit))
626                            (downcase (nth 1 bit))))
627           (if (member "CHARSET" (nth 2 bit))
628               (insert (format
629                        "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
630             (insert "\n"))
631           (insert (format "Content-transfer-encoding: %s\n"
632                           (nth 5 bit)))
633           (insert "\n")
634           (when (assoc (nth 9 bit) parts)
635             (insert (cadr (assoc (nth 9 bit) parts)))))))
636     (insert "\n--" boundary "--\n")))
637
638 (defun nnimap-find-wanted-parts (structure)
639   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
640
641 (defun nnimap-find-wanted-parts-1 (structure prefix)
642   (let ((num 1)
643         parts)
644     (while (consp (car structure))
645       (let ((sub (pop structure)))
646         (if (consp (car sub))
647             (push (nnimap-find-wanted-parts-1
648                    sub (if (string= prefix "")
649                            (number-to-string num)
650                          (format "%s.%s" prefix num)))
651                   parts)
652           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
653                 (id (if (string= prefix "")
654                         (number-to-string num)
655                       (format "%s.%s" prefix num))))
656             (setcar (nthcdr 9 sub) id)
657             (when (if (eq nnimap-fetch-partial-articles t)
658                       (equal id "1")
659                     (string-match nnimap-fetch-partial-articles type))
660               (push id parts))))
661         (incf num)))
662     (nreverse parts)))
663
664 (deffoo nnimap-request-group (group &optional server dont-check info)
665   (let ((result (nnimap-possibly-change-group
666                  ;; Don't SELECT the group if we're going to select it
667                  ;; later, anyway.
668                  (if (and (not dont-check)
669                           (assoc group nnimap-current-infos))
670                      nil
671                    group)
672                  server))
673         articles active marks high low)
674     (with-current-buffer nntp-server-buffer
675       (when result
676         (if (and dont-check
677                  (setq active (nth 2 (assoc group nnimap-current-infos))))
678             (insert (format "211 %d %d %d %S\n"
679                             (- (cdr active) (car active))
680                             (car active)
681                             (cdr active)
682                             group))
683           (with-current-buffer (nnimap-buffer)
684             (erase-buffer)
685             (let ((group-sequence
686                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
687                   (flag-sequence
688                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
689               (setf (nnimap-group nnimap-object) group)
690               (nnimap-wait-for-response flag-sequence)
691               (setq marks
692                     (nnimap-flags-to-marks
693                      (nnimap-parse-flags
694                       (list (list group-sequence flag-sequence
695                                   1 group "SELECT")))))
696               (when (and info
697                          marks)
698                 (nnimap-update-infos marks (list info))
699                 (nnimap-store-info info (gnus-active (gnus-info-group info))))
700               (goto-char (point-max))
701               (let ((uidnext (nth 5 (car marks))))
702                 (setq high (or (if uidnext
703                                    (1- uidnext)
704                                  (nth 3 (car marks)))
705                                0)
706                       low (or (nth 4 (car marks)) uidnext 1)))))
707           (erase-buffer)
708           (insert
709            (format
710             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
711         t))))
712
713 (deffoo nnimap-request-create-group (group &optional server args)
714   (when (nnimap-possibly-change-group nil server)
715     (with-current-buffer (nnimap-buffer)
716       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
717
718 (deffoo nnimap-request-delete-group (group &optional force server)
719   (when (nnimap-possibly-change-group nil server)
720     (with-current-buffer (nnimap-buffer)
721       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
722
723 (deffoo nnimap-request-rename-group (group new-name &optional server)
724   (when (nnimap-possibly-change-group nil server)
725     (with-current-buffer (nnimap-buffer)
726       (nnimap-unselect-group)
727       (car (nnimap-command "RENAME %S %S"
728                            (utf7-encode group t) (utf7-encode new-name t))))))
729
730 (defun nnimap-unselect-group ()
731   ;; Make sure we don't have this group open read/write by asking
732   ;; to examine a mailbox that doesn't exist.  This seems to be
733   ;; the only way that allows us to reliably go back to unselected
734   ;; state on Courier.
735   (nnimap-command "EXAMINE DOES.NOT.EXIST"))
736
737 (deffoo nnimap-request-expunge-group (group &optional server)
738   (when (nnimap-possibly-change-group group server)
739     (with-current-buffer (nnimap-buffer)
740       (car (nnimap-command "EXPUNGE")))))
741
742 (defun nnimap-get-flags (spec)
743   (let ((articles nil)
744         elems end)
745     (with-current-buffer (nnimap-buffer)
746       (erase-buffer)
747       (nnimap-wait-for-response (nnimap-send-command
748                                  "UID FETCH %s FLAGS" spec))
749       (setq end (point))
750       (subst-char-in-region (point-min) (point-max)
751                             ?\\ ?% t)
752       (goto-char (point-min))
753       (while (search-forward " FETCH " end t)
754         (setq elems (read (current-buffer)))
755         (push (cons (cadr (memq 'UID elems))
756                     (cadr (memq 'FLAGS elems)))
757               articles)))
758     (nreverse articles)))
759
760 (deffoo nnimap-close-group (group &optional server)
761   t)
762
763 (deffoo nnimap-request-move-article (article group server accept-form
764                                              &optional last internal-move-group)
765   (with-temp-buffer
766     (mm-disable-multibyte)
767     (when (funcall (if internal-move-group
768                        'nnimap-request-head
769                      'nnimap-request-article)
770                    article group server (current-buffer))
771       ;; If the move is internal (on the same server), just do it the easy
772       ;; way.
773       (let ((message-id (message-field-value "message-id")))
774         (if internal-move-group
775             (let ((result
776                    (with-current-buffer (nnimap-buffer)
777                      (nnimap-command "UID COPY %d %S"
778                                      article
779                                      (utf7-encode internal-move-group t)))))
780               (when (car result)
781                 (nnimap-delete-article article)
782                 (cons internal-move-group
783                       (or (nnimap-find-uid-response "COPYUID" (cadr result))
784                           (nnimap-find-article-by-message-id
785                            internal-move-group message-id)))))
786           ;; Move the article to a different method.
787           (let ((result (eval accept-form)))
788             (when result
789               (nnimap-delete-article article)
790               result)))))))
791
792 (deffoo nnimap-request-expire-articles (articles group &optional server force)
793   (cond
794    ((null articles)
795     nil)
796    ((not (nnimap-possibly-change-group group server))
797     articles)
798    ((and force
799          (eq nnmail-expiry-target 'delete))
800     (unless (nnimap-delete-article (gnus-compress-sequence articles))
801       (nnheader-message 7 "Article marked for deletion, but not expunged."))
802     nil)
803    (t
804     (let ((deletable-articles
805            (if (or force
806                    (eq nnmail-expiry-wait 'immediate))
807                articles
808              (gnus-sorted-intersection
809               articles
810               (nnimap-find-expired-articles group)))))
811       (if (null deletable-articles)
812           articles
813         (if (eq nnmail-expiry-target 'delete)
814             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
815           (setq deletable-articles
816                 (nnimap-process-expiry-targets
817                  deletable-articles group server)))
818         ;; Return the articles we didn't delete.
819         (gnus-sorted-complement articles deletable-articles))))))
820
821 (defun nnimap-process-expiry-targets (articles group server)
822   (let ((deleted-articles nil))
823     (cond
824      ;; shortcut further processing if we're going to delete the articles
825      ((eq nnmail-expiry-target 'delete)
826       (setq deleted-articles articles)
827       t)
828      ;; or just move them to another folder on the same IMAP server
829      ((and (not (functionp nnmail-expiry-target))
830            (gnus-server-equal (gnus-group-method nnmail-expiry-target)
831                               (gnus-server-to-method
832                                (format "nnimap:%s" server))))
833       (and (nnimap-possibly-change-group group server)
834            (with-current-buffer (nnimap-buffer)
835              (nnheader-message 7 "Expiring articles from %s: %s" group articles)
836              (nnimap-command
837               "UID COPY %s %S"
838               (nnimap-article-ranges (gnus-compress-sequence articles))
839               (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
840              (setq deleted-articles articles)))
841       t)
842      (t
843       (dolist (article articles)
844         (let ((target nnmail-expiry-target))
845           (with-temp-buffer
846             (mm-disable-multibyte)
847             (when (nnimap-request-article article group server (current-buffer))
848               (nnheader-message 7 "Expiring article %s:%d" group article)
849               (when (functionp target)
850                 (setq target (funcall target group)))
851               (when (and target
852                          (not (eq target 'delete)))
853                 (if (or (gnus-request-group target t)
854                         (gnus-request-create-group target))
855                     (nnmail-expiry-target-group target group)
856                   (setq target nil)))
857               (when target
858                 (push article deleted-articles))))))))
859     ;; Change back to the current group again.
860     (nnimap-possibly-change-group group server)
861     (setq deleted-articles (nreverse deleted-articles))
862     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
863     deleted-articles))
864
865 (defun nnimap-find-expired-articles (group)
866   (let ((cutoff (nnmail-expired-article-p group nil nil)))
867     (with-current-buffer (nnimap-buffer)
868       (let ((result
869              (nnimap-command
870               "UID SEARCH SENTBEFORE %s"
871               (format-time-string
872                (format "%%d-%s-%%Y"
873                        (upcase
874                         (car (rassoc (nth 4 (decode-time cutoff))
875                                      parse-time-months))))
876                cutoff))))
877         (and (car result)
878              (delete 0 (mapcar #'string-to-number
879                                (cdr (assoc "SEARCH" (cdr result))))))))))
880
881
882 (defun nnimap-find-article-by-message-id (group message-id)
883   (with-current-buffer (nnimap-buffer)
884     (erase-buffer)
885     (unless (equal group (nnimap-group nnimap-object))
886       (setf (nnimap-group nnimap-object) nil)
887       (setf (nnimap-examined nnimap-object) group)
888       (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
889     (let ((sequence
890            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
891           article result)
892       (setq result (nnimap-wait-for-response sequence))
893       (when (and result
894                  (car (setq result (nnimap-parse-response))))
895         ;; Select the last instance of the message in the group.
896         (and (setq article
897                    (car (last (assoc "SEARCH" (cdr result)))))
898              (string-to-number article))))))
899
900 (defun nnimap-delete-article (articles)
901   (with-current-buffer (nnimap-buffer)
902     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
903                     (nnimap-article-ranges articles))
904     (cond
905      ((nnimap-capability "UIDPLUS")
906       (nnimap-command "UID EXPUNGE %s"
907                       (nnimap-article-ranges articles))
908       t)
909      (nnimap-expunge
910       (nnimap-command "EXPUNGE")
911       t)
912      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
913                                 "server doesn't support UIDPLUS, so we won't "
914                                 "delete this article now"))))))
915
916 (deffoo nnimap-request-scan (&optional group server)
917   (when (and (nnimap-possibly-change-group nil server)
918              nnimap-inbox
919              nnimap-split-methods)
920     (nnheader-message 7 "nnimap %s splitting mail..." server)
921     (nnimap-split-incoming-mail)))
922
923 (defun nnimap-marks-to-flags (marks)
924   (let (flags flag)
925     (dolist (mark marks)
926       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
927         (push flag flags)))
928     flags))
929
930 (deffoo nnimap-request-update-group-status (group status &optional server)
931   (when (nnimap-possibly-change-group nil server)
932     (let ((command (assoc
933                     status
934                     '((subscribe "SUBSCRIBE")
935                       (unsubscribe "UNSUBSCRIBE")))))
936       (when command
937         (with-current-buffer (nnimap-buffer)
938           (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
939
940 (deffoo nnimap-request-set-mark (group actions &optional server)
941   (when (nnimap-possibly-change-group group server)
942     (let (sequence)
943       (with-current-buffer (nnimap-buffer)
944         (erase-buffer)
945         ;; Just send all the STORE commands without waiting for
946         ;; response.  If they're successful, they're successful.
947         (dolist (action actions)
948           (destructuring-bind (range action marks) action
949             (let ((flags (nnimap-marks-to-flags marks)))
950               (when flags
951                 (setq sequence (nnimap-send-command
952                                 "UID STORE %s %sFLAGS.SILENT (%s)"
953                                 (nnimap-article-ranges range)
954                                 (cond
955                                  ((eq action 'del) "-")
956                                  ((eq action 'add) "+")
957                                  ((eq action 'set) ""))
958                                 (mapconcat #'identity flags " ")))))))
959         ;; Wait for the last command to complete to avoid later
960         ;; syncronisation problems with the stream.
961         (when sequence
962           (nnimap-wait-for-response sequence))))))
963
964 (deffoo nnimap-request-accept-article (group &optional server last)
965   (when (nnimap-possibly-change-group nil server)
966     (nnmail-check-syntax)
967     (let ((message-id (message-field-value "message-id"))
968           sequence message)
969       (nnimap-add-cr)
970       (setq message (buffer-substring-no-properties (point-min) (point-max)))
971       (with-current-buffer (nnimap-buffer)
972         ;; If we have this group open read-only, then unselect it
973         ;; before appending to it.
974         (when (equal (nnimap-examined nnimap-object) group)
975           (nnimap-unselect-group))
976         (erase-buffer)
977         (setq sequence (nnimap-send-command
978                         "APPEND %S {%d}" (utf7-encode group t)
979                         (length message)))
980         (unless nnimap-streaming
981           (nnimap-wait-for-connection "^[+]"))
982         (process-send-string (get-buffer-process (current-buffer)) message)
983         (process-send-string (get-buffer-process (current-buffer))
984                              (if (nnimap-newlinep nnimap-object)
985                                  "\n"
986                                "\r\n"))
987         (let ((result (nnimap-get-response sequence)))
988           (if (not (nnimap-ok-p result))
989               (progn
990                 (nnheader-report 'nnimap "%s" result)
991                 nil)
992             (cons group
993                   (or (nnimap-find-uid-response "APPENDUID" (car result))
994                       (nnimap-find-article-by-message-id
995                        group message-id)))))))))
996
997 (defun nnimap-ok-p (value)
998   (and (consp value)
999        (consp (car value))
1000        (equal (caar value) "OK")))
1001
1002 (defun nnimap-find-uid-response (name list)
1003   (let ((result (car (last (nnimap-find-response-element name list)))))
1004     (and result
1005          (string-to-number result))))
1006
1007 (defun nnimap-find-response-element (name list)
1008   (let (result)
1009     (dolist (elem list)
1010       (when (and (consp elem)
1011                  (equal name (car elem)))
1012         (setq result elem)))
1013     result))
1014
1015 (deffoo nnimap-request-replace-article (article group buffer)
1016   (let (group-art)
1017     (when (and (nnimap-possibly-change-group group nil)
1018                ;; Put the article into the group.
1019                (with-current-buffer buffer
1020                  (setq group-art
1021                        (nnimap-request-accept-article group nil t))))
1022       (nnimap-delete-article (list article))
1023       ;; Return the new article number.
1024       (cdr group-art))))
1025
1026 (defun nnimap-add-cr ()
1027   (goto-char (point-min))
1028   (while (re-search-forward "\r?\n" nil t)
1029     (replace-match "\r\n" t t)))
1030
1031 (defun nnimap-get-groups ()
1032   (erase-buffer)
1033   (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1034         groups)
1035     (nnimap-wait-for-response sequence)
1036     (subst-char-in-region (point-min) (point-max)
1037                           ?\\ ?% t)
1038     (goto-char (point-min))
1039     (nnimap-unfold-quoted-lines)
1040     (goto-char (point-min))
1041     (while (search-forward "* LIST " nil t)
1042       (let ((flags (read (current-buffer)))
1043             (separator (read (current-buffer)))
1044             (group (read (current-buffer))))
1045         (unless (member '%NoSelect flags)
1046           (push (if (stringp group)
1047                     group
1048                   (format "%s" group))
1049                 groups))))
1050     (nreverse groups)))
1051
1052 (deffoo nnimap-request-list (&optional server)
1053   (nnimap-possibly-change-group nil server)
1054   (with-current-buffer nntp-server-buffer
1055     (erase-buffer)
1056     (let ((groups
1057            (with-current-buffer (nnimap-buffer)
1058              (nnimap-get-groups)))
1059           sequences responses)
1060       (when groups
1061         (with-current-buffer (nnimap-buffer)
1062           (setf (nnimap-group nnimap-object) nil)
1063           (dolist (group groups)
1064             (setf (nnimap-examined nnimap-object) group)
1065             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
1066                         group)
1067                   sequences))
1068           (nnimap-wait-for-response (caar sequences))
1069           (setq responses
1070                 (nnimap-get-responses (mapcar #'car sequences))))
1071         (dolist (response responses)
1072           (let* ((sequence (car response))
1073                  (response (cadr response))
1074                  (group (cadr (assoc sequence sequences))))
1075             (when (and group
1076                        (equal (caar response) "OK"))
1077               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1078                     highest exists)
1079                 (dolist (elem response)
1080                   (when (equal (cadr elem) "EXISTS")
1081                     (setq exists (string-to-number (car elem)))))
1082                 (when uidnext
1083                   (setq highest (1- (string-to-number (car uidnext)))))
1084                 (cond
1085                  ((null highest)
1086                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1087                  ((zerop exists)
1088                   ;; Empty group.
1089                   (insert (format "%S %d %d y\n"
1090                                   (utf7-decode group t) highest (1+ highest))))
1091                  (t
1092                   ;; Return the widest possible range.
1093                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
1094                                   (or highest exists)))))))))
1095         t))))
1096
1097 (deffoo nnimap-request-newgroups (date &optional server)
1098   (nnimap-possibly-change-group nil server)
1099   (with-current-buffer nntp-server-buffer
1100     (erase-buffer)
1101     (dolist (group (with-current-buffer (nnimap-buffer)
1102                      (nnimap-get-groups)))
1103       (unless (assoc group nnimap-current-infos)
1104         ;; Insert dummy numbers here -- they don't matter.
1105         (insert (format "%S 0 1 y\n" group))))
1106     t))
1107
1108 (deffoo nnimap-retrieve-group-data-early (server infos)
1109   (when (nnimap-possibly-change-group nil server)
1110     (with-current-buffer (nnimap-buffer)
1111       (erase-buffer)
1112       (setf (nnimap-group nnimap-object) nil)
1113       (let ((qresyncp (nnimap-capability "QRESYNC"))
1114             params groups sequences active uidvalidity modseq group)
1115         ;; Go through the infos and gather the data needed to know
1116         ;; what and how to request the data.
1117         (dolist (info infos)
1118           (setq params (gnus-info-params info)
1119                 group (gnus-group-real-name (gnus-info-group info))
1120                 active (cdr (assq 'active params))
1121                 uidvalidity (cdr (assq 'uidvalidity params))
1122                 modseq (cdr (assq 'modseq params)))
1123           (setf (nnimap-examined nnimap-object) group)
1124           (if (and qresyncp
1125                    uidvalidity
1126                    modseq)
1127               (push
1128                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1129                                           (utf7-encode group t)
1130                                           (nnimap-quirk "QRESYNC")
1131                                           uidvalidity modseq)
1132                      'qresync
1133                      nil group 'qresync)
1134                sequences)
1135             (let ((start
1136                    (if (and active uidvalidity)
1137                        ;; Fetch the last 100 flags.
1138                        (max 1 (- (cdr active) 100))
1139                      1))
1140                   (command
1141                    (if uidvalidity
1142                        "EXAMINE"
1143                      ;; If we don't have a UIDVALIDITY, then this is
1144                      ;; the first time we've seen the group, so we
1145                      ;; have to do a SELECT (which is slower than an
1146                      ;; examine), but will tell us whether the group
1147                      ;; is read-only or not.
1148                      "SELECT")))
1149               (push (list (nnimap-send-command "%s %S" command
1150                                                (utf7-encode group t))
1151                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1152                           start group command)
1153                     sequences))))
1154         sequences))))
1155
1156 (defun nnimap-quirk (command)
1157   (let ((quirk (assoc command nnimap-quirks)))
1158     ;; If this server is of a type that matches a quirk, then return
1159     ;; the "quirked" command instead of the proper one.
1160     (if (or (null quirk)
1161             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1162         command
1163       (nth 2 quirk))))
1164
1165 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1166   (when (and sequences
1167              (nnimap-possibly-change-group nil server))
1168     (with-current-buffer (nnimap-buffer)
1169       ;; Wait for the final data to trickle in.
1170       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1171                                           (caar sequences)
1172                                         (cadar sequences))
1173                                       t)
1174         ;; Now we should have most of the data we need, no matter
1175         ;; whether we're QRESYNCING, fetching all the flags from
1176         ;; scratch, or just fetching the last 100 flags per group.
1177         (nnimap-update-infos (nnimap-flags-to-marks
1178                               (nnimap-parse-flags
1179                                (nreverse sequences)))
1180                              infos)
1181         ;; Finally, just return something resembling an active file in
1182         ;; the nntp buffer, so that the agent can save the info, too.
1183         (with-current-buffer nntp-server-buffer
1184           (erase-buffer)
1185           (dolist (info infos)
1186             (let* ((group (gnus-info-group info))
1187                    (active (gnus-active group)))
1188               (when active
1189                 (insert (format "%S %d %d y\n"
1190                                 (gnus-group-real-name group)
1191                                 (cdr active)
1192                                 (car active)))))))))))
1193
1194 (defun nnimap-update-infos (flags infos)
1195   (dolist (info infos)
1196     (let* ((group (gnus-group-real-name (gnus-info-group info)))
1197            (marks (cdr (assoc group flags))))
1198       (when marks
1199         (nnimap-update-info info marks)))))
1200
1201 (defun nnimap-update-info (info marks)
1202   (destructuring-bind (existing flags high low uidnext start-article
1203                                 permanent-flags uidvalidity
1204                                 vanished highestmodseq) marks
1205     (cond
1206      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1207      ;; completely empty groups.
1208      ((and (not existing)
1209            (not uidnext))
1210       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1211         (when active
1212           (gnus-set-active (gnus-info-group info) active))))
1213      ;; We have a mismatch between the old and new UIDVALIDITY
1214      ;; identifiers, so we have to re-request the group info (the next
1215      ;; time).  This virtually never happens.
1216      ((let ((old-uidvalidity
1217              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1218         (and old-uidvalidity
1219              (not (equal old-uidvalidity uidvalidity))
1220              (> start-article 1)))
1221       (gnus-group-remove-parameter info 'uidvalidity)
1222       (gnus-group-remove-parameter info 'modseq))
1223      ;; We have the data needed to update.
1224      (t
1225       (let* ((group (gnus-info-group info))
1226              (completep (and start-article
1227                              (= start-article 1)))
1228              (active (or (gnus-active group)
1229                          (cdr (assq 'active (gnus-info-params info))))))
1230         (when uidnext
1231           (setq high (1- uidnext)))
1232         ;; First set the active ranges based on high/low.
1233         (gnus-set-active
1234          group
1235          (if (or completep
1236                  (not (gnus-active group)))
1237              (cond
1238               (active
1239                (cons (min (or low (car active))
1240                           (car active))
1241                      (max (or high (cdr active))
1242                           (cdr active))))
1243               ((and low high)
1244                (cons low high))
1245               (uidnext
1246                ;; No articles in this group.
1247                (cons uidnext (1- uidnext)))
1248               (start-article
1249                (cons start-article (1- start-article)))
1250               (t
1251                ;; No articles and no uidnext.
1252                nil))
1253            (cons (car active)
1254                  (or high (1- uidnext)))))
1255         ;; See whether this is a read-only group.
1256         (unless (eq permanent-flags 'not-scanned)
1257           (gnus-group-set-parameter
1258            info 'permanent-flags
1259            (and (or (memq '%* permanent-flags)
1260                     (memq '%Seen permanent-flags))
1261                 permanent-flags)))
1262         ;; Update marks and read articles if this isn't a
1263         ;; read-only IMAP group.
1264         (when (setq permanent-flags
1265                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1266           (if (and highestmodseq
1267                    (not start-article))
1268               ;; We've gotten the data by QRESYNCing.
1269               (nnimap-update-qresync-info
1270                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1271             ;; Do normal non-QRESYNC flag updates.
1272             ;; Update the list of read articles.
1273             (let* ((unread
1274                     (gnus-compress-sequence
1275                      (gnus-set-difference
1276                       (gnus-set-difference
1277                        existing
1278                        (cdr (assoc '%Seen flags)))
1279                       (cdr (assoc '%Flagged flags)))))
1280                    (read (gnus-range-difference
1281                           (cons start-article high) unread)))
1282               (when (> start-article 1)
1283                 (setq read
1284                       (gnus-range-nconcat
1285                        (if (> start-article 1)
1286                            (gnus-sorted-range-intersection
1287                             (cons 1 (1- start-article))
1288                             (gnus-info-read info))
1289                          (gnus-info-read info))
1290                        read)))
1291               (when (or (not (listp permanent-flags))
1292                         (memq '%Seen permanent-flags))
1293                 (gnus-info-set-read info read))
1294               ;; Update the marks.
1295               (setq marks (gnus-info-marks info))
1296               (dolist (type (cdr nnimap-mark-alist))
1297                 (when (or (not (listp permanent-flags))
1298                           (memq (car (assoc (caddr type) flags))
1299                                 permanent-flags)
1300                           (memq '%* permanent-flags))
1301                   (let ((old-marks (assoc (car type) marks))
1302                         (new-marks
1303                          (gnus-compress-sequence
1304                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1305                                    (assoc (intern (cadr type) obarray) flags)
1306                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1307                     (setq marks (delq old-marks marks))
1308                     (pop old-marks)
1309                     (when (and old-marks
1310                                (> start-article 1))
1311                       (setq old-marks (gnus-range-difference
1312                                        old-marks
1313                                        (cons start-article high)))
1314                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1315                     (when new-marks
1316                       (push (cons (car type) new-marks) marks)))))
1317               (gnus-info-set-marks info marks t))))
1318         ;; Tell Gnus whether there are any \Recent messages in any of
1319         ;; the groups.
1320         (let ((recent (cdr (assoc '%Recent flags))))
1321           (when (and active recent)
1322             (while recent
1323               (when (> (car recent) (cdr active))
1324                 (push (list (cons (gnus-group-real-name group) 0))
1325                       nnmail-split-history)
1326                 (setq recent nil))
1327               (pop recent))))
1328         ;; Note the active level for the next run-through.
1329         (gnus-group-set-parameter info 'active (gnus-active group))
1330         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1331         (gnus-group-set-parameter info 'modseq highestmodseq)
1332         (nnimap-store-info info (gnus-active group)))))))
1333
1334 (defun nnimap-update-qresync-info (info existing vanished flags)
1335   ;; Add all the vanished articles to the list of read articles.
1336   (gnus-info-set-read
1337    info
1338    (gnus-add-to-range
1339     (gnus-add-to-range
1340      (gnus-range-add (gnus-info-read info)
1341                      vanished)
1342      (cdr (assq '%Flagged flags)))
1343     (cdr (assq '%Seen flags))))
1344   (let ((marks (gnus-info-marks info)))
1345     (dolist (type (cdr nnimap-mark-alist))
1346       (let ((ticks (assoc (car type) marks))
1347             (new-marks
1348              (cdr (or (assoc (caddr type) flags) ; %Flagged
1349                       (assoc (intern (cadr type) obarray) flags)
1350                       (assoc (cadr type) flags))))) ; "\Flagged"
1351         (setq marks (delq ticks marks))
1352         (pop ticks)
1353         ;; Add the new marks we got.
1354         (setq ticks (gnus-add-to-range ticks new-marks))
1355         ;; Remove the marks from messages that don't have them.
1356         (setq ticks (gnus-remove-from-range
1357                      ticks
1358                      (gnus-compress-sequence
1359                       (gnus-sorted-complement existing new-marks))))
1360         (when ticks
1361           (push (cons (car type) ticks) marks)))
1362       (gnus-info-set-marks info marks t))))
1363
1364 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1365   (if (zerop (length irange))
1366       nil
1367     (let ((result nil))
1368       (dolist (elem (split-string irange ","))
1369         (push
1370          (if (string-match ":" elem)
1371              (let ((numbers (split-string elem ":")))
1372                (cons (string-to-number (car numbers))
1373                      (string-to-number (cadr numbers))))
1374            (string-to-number elem))
1375          result))
1376       (nreverse result))))
1377
1378 (defun nnimap-store-info (info active)
1379   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1380          (entry (assoc group nnimap-current-infos)))
1381     (if entry
1382         (setcdr entry (list info active))
1383       (push (list group info active) nnimap-current-infos))))
1384
1385 (defun nnimap-flags-to-marks (groups)
1386   (let (data group totalp uidnext articles start-article mark permanent-flags
1387              uidvalidity vanished highestmodseq)
1388     (dolist (elem groups)
1389       (setq group (car elem)
1390             uidnext (nth 1 elem)
1391             start-article (nth 2 elem)
1392             permanent-flags (nth 3 elem)
1393             uidvalidity (nth 4 elem)
1394             vanished (nth 5 elem)
1395             highestmodseq (nth 6 elem)
1396             articles (nthcdr 7 elem))
1397       (let ((high (caar articles))
1398             marks low existing)
1399         (dolist (article articles)
1400           (setq low (car article))
1401           (push (car article) existing)
1402           (dolist (flag (cdr article))
1403             (setq mark (assoc flag marks))
1404             (if (not mark)
1405                 (push (list flag (car article)) marks)
1406               (setcdr mark (cons (car article) (cdr mark))))))
1407         (push (list group existing marks high low uidnext start-article
1408                     permanent-flags uidvalidity vanished highestmodseq)
1409               data)))
1410     data))
1411
1412 (defun nnimap-parse-flags (sequences)
1413   (goto-char (point-min))
1414   ;; Change \Delete etc to %Delete, so that the reader can read it.
1415   (subst-char-in-region (point-min) (point-max)
1416                         ?\\ ?% t)
1417   (let (start end articles groups uidnext elems permanent-flags
1418               uidvalidity vanished highestmodseq)
1419     (dolist (elem sequences)
1420       (destructuring-bind (group-sequence flag-sequence totalp group command)
1421           elem
1422         (setq start (point))
1423         (when (and
1424                ;; The EXAMINE was successful.
1425                (search-forward (format "\n%d OK " group-sequence) nil t)
1426                (progn
1427                  (forward-line 1)
1428                  (setq end (point))
1429                  (goto-char start)
1430                  (setq permanent-flags
1431                        (if (equal command "SELECT")
1432                            (and (search-forward "PERMANENTFLAGS "
1433                                                 (or end (point-min)) t)
1434                                 (read (current-buffer)))
1435                          'not-scanned))
1436                  (goto-char start)
1437                  (setq uidnext
1438                        (and (search-forward "UIDNEXT "
1439                                             (or end (point-min)) t)
1440                             (read (current-buffer))))
1441                  (goto-char start)
1442                  (setq uidvalidity
1443                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1444                                                (or end (point-min)) t)
1445                             ;; Store UIDVALIDITY as a string, as it's
1446                             ;; too big for 32-bit Emacsen, usually.
1447                             (match-string 1)))
1448                  (goto-char start)
1449                  (setq vanished
1450                        (and (eq flag-sequence 'qresync)
1451                             (re-search-forward "^\\* VANISHED .* \\([0-9:,]+\\)"
1452                                                (or end (point-min)) t)
1453                             (match-string 1)))
1454                  (goto-char start)
1455                  (setq highestmodseq
1456                        (and (search-forward "HIGHESTMODSEQ "
1457                                             (or end (point-min)) t)
1458                             (read (current-buffer))))
1459                  (goto-char end)
1460                  (forward-line -1))
1461                ;; The UID FETCH FLAGS was successful.
1462                (or (eq flag-sequence 'qresync)
1463                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1464           (if (eq flag-sequence 'qresync)
1465               (progn
1466                 (goto-char start)
1467                 (setq start end))
1468             (setq start (point))
1469             (goto-char end))
1470           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1471             (setq elems (read (current-buffer)))
1472             (push (cons (cadr (memq 'UID elems))
1473                         (cadr (memq 'FLAGS elems)))
1474                   articles))
1475           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1476                              vanished highestmodseq)
1477                        articles)
1478                 groups)
1479           (goto-char end)
1480           (setq articles nil))))
1481     groups))
1482
1483 (defun nnimap-find-process-buffer (buffer)
1484   (cadr (assoc buffer nnimap-connection-alist)))
1485
1486 (deffoo nnimap-request-post (&optional server)
1487   (setq nnimap-status-string "Read-only server")
1488   nil)
1489
1490 (declare-function gnus-fetch-headers "gnus-sum"
1491                   (articles &optional limit force-new dependencies))
1492
1493 (deffoo nnimap-request-thread (header)
1494   (let* ((id (mail-header-id header))
1495          (refs (split-string
1496                 (or (mail-header-references header)
1497                     "")))
1498          (cmd (let ((value
1499                      (format
1500                       "(OR HEADER REFERENCES %s HEADER Message-Id %s)"
1501                       id id)))
1502                 (dolist (refid refs value)
1503                   (setq value (format
1504                                "(OR (OR HEADER Message-Id %s HEADER REFERENCES %s) %s)"
1505                                refid refid value)))))
1506          (result (with-current-buffer (nnimap-buffer)
1507                    (nnimap-command  "UID SEARCH %s" cmd))))
1508     (gnus-fetch-headers
1509      (and (car result) (delete 0 (mapcar #'string-to-number
1510                                          (cdr (assoc "SEARCH" (cdr result))))))
1511      nil t)))
1512
1513 (defun nnimap-possibly-change-group (group server)
1514   (let ((open-result t))
1515     (when (and server
1516                (not (nnimap-server-opened server)))
1517       (setq open-result (nnimap-open-server server)))
1518     (cond
1519      ((not open-result)
1520       nil)
1521      ((not group)
1522       t)
1523      (t
1524       (with-current-buffer (nnimap-buffer)
1525         (if (equal group (nnimap-group nnimap-object))
1526             t
1527           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1528             (when (car result)
1529               (setf (nnimap-group nnimap-object) group
1530                     (nnimap-select-result nnimap-object) result)
1531               result))))))))
1532
1533 (defun nnimap-find-connection (buffer)
1534   "Find the connection delivering to BUFFER."
1535   (let ((entry (assoc buffer nnimap-connection-alist)))
1536     (when entry
1537       (if (and (buffer-name (cadr entry))
1538                (get-buffer-process (cadr entry))
1539                (memq (process-status (get-buffer-process (cadr entry)))
1540                      '(open run)))
1541           (get-buffer-process (cadr entry))
1542         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1543         nil))))
1544
1545 (defvar nnimap-sequence 0)
1546
1547 (defun nnimap-send-command (&rest args)
1548   (process-send-string
1549    (get-buffer-process (current-buffer))
1550    (nnimap-log-command
1551     (format "%d %s%s\n"
1552             (incf nnimap-sequence)
1553             (apply #'format args)
1554             (if (nnimap-newlinep nnimap-object)
1555                 ""
1556               "\r"))))
1557   ;; Some servers apparently can't have many outstanding
1558   ;; commands, so throttle them.
1559   (unless nnimap-streaming
1560     (nnimap-wait-for-response nnimap-sequence))
1561   nnimap-sequence)
1562
1563 (defun nnimap-log-command (command)
1564   (with-current-buffer (get-buffer-create "*imap log*")
1565     (goto-char (point-max))
1566     (insert (format-time-string "%H:%M:%S") " " command))
1567   command)
1568
1569 (defun nnimap-command (&rest args)
1570   (erase-buffer)
1571   (setf (nnimap-last-command-time nnimap-object) (current-time))
1572   (let* ((sequence (apply #'nnimap-send-command args))
1573          (response (nnimap-get-response sequence)))
1574     (if (equal (caar response) "OK")
1575         (cons t response)
1576       (nnheader-report 'nnimap "%s"
1577                        (mapconcat (lambda (a)
1578                                     (format "%s" a))
1579                                   (car response) " "))
1580       nil)))
1581
1582 (defun nnimap-get-response (sequence)
1583   (nnimap-wait-for-response sequence)
1584   (nnimap-parse-response))
1585
1586 (defun nnimap-wait-for-connection (&optional regexp)
1587   (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1588
1589 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1590   (let ((process (get-buffer-process (current-buffer))))
1591     (goto-char (point-min))
1592     (while (and (memq (process-status process)
1593                       '(open run))
1594                 (not (re-search-forward regexp nil t)))
1595       (nnheader-accept-process-output process)
1596       (goto-char (point-min)))
1597     (forward-line -1)
1598     (and (looking-at (or response-regexp regexp))
1599          (match-string 1))))
1600
1601 (defun nnimap-wait-for-response (sequence &optional messagep)
1602   (let ((process (get-buffer-process (current-buffer)))
1603         openp)
1604     (condition-case nil
1605         (progn
1606           (goto-char (point-max))
1607           (while (and (setq openp (memq (process-status process)
1608                                         '(open run)))
1609                       (progn
1610                         ;; Skip past any "*" lines that the server has
1611                         ;; output.
1612                         (while (and (not (bobp))
1613                                     (progn
1614                                       (forward-line -1)
1615                                       (looking-at "\\*"))))
1616                         (not (looking-at (format "%d " sequence)))))
1617             (when messagep
1618               (nnheader-message 7 "nnimap read %dk" (/ (buffer-size) 1000)))
1619             (nnheader-accept-process-output process)
1620             (goto-char (point-max)))
1621           openp)
1622       (quit
1623        ;; The user hit C-g while we were waiting: kill the process, in case
1624        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1625        ;; NAT routers).
1626        (delete-process process)
1627        nil))))
1628
1629 (defun nnimap-parse-response ()
1630   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1631         result)
1632     (dolist (line lines)
1633       (push (cdr (nnimap-parse-line line)) result))
1634     ;; Return the OK/error code first, and then all the "continuation
1635     ;; lines" afterwards.
1636     (cons (pop result)
1637           (nreverse result))))
1638
1639 ;; Parse an IMAP response line lightly.  They look like
1640 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1641 ;; the lines into a list of strings and lists of string.
1642 (defun nnimap-parse-line (line)
1643   (let (char result)
1644     (with-temp-buffer
1645       (mm-disable-multibyte)
1646       (insert line)
1647       (goto-char (point-min))
1648       (while (not (eobp))
1649         (if (eql (setq char (following-char)) ? )
1650             (forward-char 1)
1651           (push
1652            (cond
1653             ((eql char ?\[)
1654              (split-string
1655               (buffer-substring
1656                (1+ (point))
1657                (if (search-forward "]" (line-end-position) 'move)
1658                    (1- (point))
1659                  (point)))))
1660             ((eql char ?\()
1661              (split-string
1662               (buffer-substring
1663                (1+ (point))
1664                (if (search-forward ")" (line-end-position) 'move)
1665                    (1- (point))
1666                  (point)))))
1667             ((eql char ?\")
1668              (forward-char 1)
1669              (buffer-substring
1670               (point)
1671               (1- (or (search-forward "\"" (line-end-position) 'move)
1672                       (point)))))
1673             (t
1674              (buffer-substring (point) (if (search-forward " " nil t)
1675                                            (1- (point))
1676                                          (goto-char (point-max))))))
1677            result)))
1678       (nreverse result))))
1679
1680 (defun nnimap-last-response-string ()
1681   (save-excursion
1682     (forward-line 1)
1683     (let ((end (point)))
1684       (forward-line -1)
1685       (when (not (bobp))
1686         (forward-line -1)
1687         (while (and (not (bobp))
1688                     (eql (following-char) ?*))
1689           (forward-line -1))
1690         (unless (eql (following-char) ?*)
1691           (forward-line 1)))
1692       (buffer-substring (point) end))))
1693
1694 (defun nnimap-get-responses (sequences)
1695   (let (responses)
1696     (dolist (sequence sequences)
1697       (goto-char (point-min))
1698       (when (re-search-forward (format "^%d " sequence) nil t)
1699         (push (list sequence (nnimap-parse-response))
1700               responses)))
1701     responses))
1702
1703 (defvar nnimap-incoming-split-list nil)
1704
1705 (defun nnimap-fetch-inbox (articles)
1706   (erase-buffer)
1707   (nnimap-wait-for-response
1708    (nnimap-send-command
1709     "UID FETCH %s %s"
1710     (nnimap-article-ranges articles)
1711     (format "(UID %s%s)"
1712             (format
1713              (if (nnimap-ver4-p)
1714                  "BODY.PEEK[HEADER] BODY.PEEK"
1715                "RFC822.PEEK"))
1716             (if nnimap-split-download-body-default
1717                 "[]"
1718               "[1]")))
1719    t))
1720
1721 (defun nnimap-split-incoming-mail ()
1722   (with-current-buffer (nnimap-buffer)
1723     (let ((nnimap-incoming-split-list nil)
1724           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1725                                     nnmail-split-methods
1726                                   nnimap-split-methods))
1727           (nnmail-split-fancy (or nnimap-split-fancy
1728                                   nnmail-split-fancy))
1729           (nnmail-inhibit-default-split-group t)
1730           (groups (nnimap-get-groups))
1731           new-articles)
1732       (erase-buffer)
1733       (nnimap-command "SELECT %S" nnimap-inbox)
1734       (setf (nnimap-group nnimap-object) nnimap-inbox)
1735       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1736       (when new-articles
1737         (nnimap-fetch-inbox new-articles)
1738         (nnimap-transform-split-mail)
1739         (nnheader-ms-strip-cr)
1740         (nnmail-cache-open)
1741         (nnmail-split-incoming (current-buffer)
1742                                #'nnimap-save-mail-spec
1743                                nil nil
1744                                #'nnimap-dummy-active-number
1745                                #'nnimap-save-mail-spec)
1746         (when nnimap-incoming-split-list
1747           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1748                 sequences junk-articles)
1749             ;; Create any groups that doesn't already exist on the
1750             ;; server first.
1751             (dolist (spec specs)
1752               (when (and (not (member (car spec) groups))
1753                          (not (eq (car spec) 'junk)))
1754                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1755             ;; Then copy over all the messages.
1756             (erase-buffer)
1757             (dolist (spec specs)
1758               (let ((group (car spec))
1759                     (ranges (cdr spec)))
1760                 (if (eq group 'junk)
1761                     (setq junk-articles ranges)
1762                   (push (list (nnimap-send-command
1763                                "UID COPY %s %S"
1764                                (nnimap-article-ranges ranges)
1765                                (utf7-encode group t))
1766                               ranges)
1767                         sequences))))
1768             ;; Wait for the last COPY response...
1769             (when sequences
1770               (nnimap-wait-for-response (caar sequences))
1771               ;; And then mark the successful copy actions as deleted,
1772               ;; and possibly expunge them.
1773               (nnimap-mark-and-expunge-incoming
1774                (nnimap-parse-copied-articles sequences)))
1775             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1776
1777 (defun nnimap-mark-and-expunge-incoming (range)
1778   (when range
1779     (setq range (nnimap-article-ranges range))
1780     (erase-buffer)
1781     (let ((sequence
1782            (nnimap-send-command
1783             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1784       (cond
1785        ;; If the server supports it, we now delete the message we have
1786        ;; just copied over.
1787        ((nnimap-capability "UIDPLUS")
1788         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1789        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1790        ;; user has configured it.
1791        (nnimap-expunge
1792         (setq sequence (nnimap-send-command "EXPUNGE"))))
1793       (nnimap-wait-for-response sequence))))
1794
1795 (defun nnimap-parse-copied-articles (sequences)
1796   (let (sequence copied range)
1797     (goto-char (point-min))
1798     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1799       (setq sequence (string-to-number (match-string 1)))
1800       (when (setq range (cadr (assq sequence sequences)))
1801         (push (gnus-uncompress-range range) copied)))
1802     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1803
1804 (defun nnimap-new-articles (flags)
1805   (let (new)
1806     (dolist (elem flags)
1807       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1808                                       (cdr elem))
1809         (push (car elem) new)))
1810     (gnus-compress-sequence (nreverse new))))
1811
1812 (defun nnimap-make-split-specs (list)
1813   (let ((specs nil)
1814         entry)
1815     (dolist (elem list)
1816       (destructuring-bind (article spec) elem
1817         (dolist (group (delete nil (mapcar #'car spec)))
1818           (unless (setq entry (assoc group specs))
1819             (push (setq entry (list group)) specs))
1820           (setcdr entry (cons article (cdr entry))))))
1821     (dolist (entry specs)
1822       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1823     specs))
1824
1825 (defun nnimap-transform-split-mail ()
1826   (goto-char (point-min))
1827   (let (article bytes)
1828     (block nil
1829       (while (not (eobp))
1830         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1831           (delete-region (point) (progn (forward-line 1) (point)))
1832           (when (eobp)
1833             (return)))
1834         (setq article (match-string 1)
1835               bytes (nnimap-get-length))
1836         (delete-region (line-beginning-position) (line-end-position))
1837         ;; Insert MMDF separator, and a way to remember what this
1838         ;; article UID is.
1839         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1840         (forward-char (1+ bytes))
1841         (setq bytes (nnimap-get-length))
1842         (delete-region (line-beginning-position) (line-end-position))
1843         ;; There's a body; skip past that.
1844         (when bytes
1845           (forward-char (1+ bytes))
1846           (delete-region (line-beginning-position) (line-end-position)))))))
1847
1848 (defun nnimap-dummy-active-number (group &optional server)
1849   1)
1850
1851 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1852   (let (article)
1853     (goto-char (point-min))
1854     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1855         (error "Invalid nnimap mail")
1856       (setq article (string-to-number (match-string 1))))
1857     (push (list article
1858                 (if (eq group-art 'junk)
1859                     (list (cons 'junk 1))
1860                   group-art))
1861           nnimap-incoming-split-list)))
1862
1863 (provide 'nnimap)
1864
1865 ;;; nnimap.el ends here