Make nnimap message better when initially fetching data
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010-2012 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   ;; In Emacs 24, `open-protocol-stream' is an autoloaded alias for
36   ;; `make-network-stream'.
37   (unless (fboundp 'open-protocol-stream)
38     (require 'proto-stream)))
39
40 (eval-when-compile
41   (require 'cl))
42
43 (require 'nnheader)
44 (require 'gnus-util)
45 (require 'gnus)
46 (require 'nnoo)
47 (require 'netrc)
48 (require 'utf7)
49 (require 'tls)
50 (require 'parse-time)
51 (require 'nnmail)
52
53 (autoload 'auth-source-forget+ "auth-source")
54 (autoload 'auth-source-search "auth-source")
55
56 (nnoo-declare nnimap)
57
58 (defvoo nnimap-address nil
59   "The address of the IMAP server.")
60
61 (defvoo nnimap-user nil
62   "Username to use for authentication to the IMAP server.")
63
64 (defvoo nnimap-server-port nil
65   "The IMAP port used.
66 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
67 it will default to `imap'.")
68
69 (defvoo nnimap-stream 'undecided
70   "How nnimap talks to the IMAP server.
71 The value should be either `undecided', `ssl' or `tls',
72 `network', `starttls', `plain', or `shell'.
73
74 If the value is `undecided', nnimap tries `ssl' first, then falls
75 back on `network'.")
76
77 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
78                                  (if (listp imap-shell-program)
79                                      (car imap-shell-program)
80                                    imap-shell-program)
81                                "ssh %s imapd"))
82
83 (defvoo nnimap-inbox nil
84   "The mail box where incoming mail arrives and should be split out of.
85 For example, \"INBOX\".")
86
87 (defvoo nnimap-split-methods nil
88   "How mail is split.
89 Uses the same syntax as `nnmail-split-methods'.")
90
91 (defvoo nnimap-split-fancy nil
92   "Uses the same syntax as `nnmail-split-fancy'.")
93
94 (defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
95   "Articles with the flags in the list will not be considered when splitting.")
96
97 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
98                         "Emacs 24.1")
99
100 (defvoo nnimap-authenticator nil
101   "How nnimap authenticate itself to the server.
102 Possible choices are nil (use default methods) or `anonymous'.")
103
104 (defvoo nnimap-expunge t
105   "If non-nil, expunge articles after deleting them.
106 This is always done if the server supports UID EXPUNGE, but it's
107 not done by default on servers that doesn't support that command.")
108
109 (defvoo nnimap-streaming t
110   "If non-nil, try to use streaming commands with IMAP servers.
111 Switching this off will make nnimap slower, but it helps with
112 some servers.")
113
114 (defvoo nnimap-connection-alist nil)
115
116 (defvoo nnimap-current-infos nil)
117
118 (defvoo nnimap-fetch-partial-articles nil
119   "If non-nil, Gnus will fetch partial articles.
120 If t, nnimap will fetch only the first part.  If a string, it
121 will fetch all parts that have types that match that string.  A
122 likely value would be \"text/\" to automatically fetch all
123 textual parts.")
124
125 (defvar nnimap-process nil)
126
127 (defvar nnimap-status-string "")
128
129 (defvar nnimap-split-download-body-default nil
130   "Internal variable with default value for `nnimap-split-download-body'.")
131
132 (defvar nnimap-keepalive-timer nil)
133 (defvar nnimap-process-buffers nil)
134
135 (defstruct nnimap
136   group process commands capabilities select-result newlinep server
137   last-command-time greeting examined stream-type initial-resync)
138
139 (defvar nnimap-object nil)
140
141 (defvar nnimap-mark-alist
142   '((read "\\Seen" %Seen)
143     (tick "\\Flagged" %Flagged)
144     (reply "\\Answered" %Answered)
145     (expire "gnus-expire")
146     (dormant "gnus-dormant")
147     (score "gnus-score")
148     (save "gnus-save")
149     (download "gnus-download")
150     (forward "gnus-forward")))
151
152 (defvar nnimap-quirks
153   '(("QRESYNC" "Zimbra" "QRESYNC ")))
154
155 (defvar nnimap-inhibit-logging nil)
156
157 (defun nnimap-buffer ()
158   (nnimap-find-process-buffer nntp-server-buffer))
159
160 (defun nnimap-header-parameters ()
161   (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
162           (format
163            (if (nnimap-ver4-p)
164                "BODY.PEEK[HEADER.FIELDS %s]"
165              "RFC822.HEADER.LINES %s")
166            (append '(Subject From Date Message-Id
167                              References In-Reply-To Xref)
168                    nnmail-extra-headers))))
169
170 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
171   (when group
172     (setq group (nnimap-decode-gnus-group group)))
173   (with-current-buffer nntp-server-buffer
174     (erase-buffer)
175     (when (nnimap-possibly-change-group group server)
176       (with-current-buffer (nnimap-buffer)
177         (erase-buffer)
178         (nnimap-wait-for-response
179          (nnimap-send-command
180           "UID FETCH %s %s"
181           (nnimap-article-ranges (gnus-compress-sequence articles))
182           (nnimap-header-parameters))
183          t)
184         (nnimap-transform-headers)
185         (nnheader-remove-cr-followed-by-lf))
186       (insert-buffer-substring
187        (nnimap-find-process-buffer (current-buffer))))
188     'headers))
189
190 (defun nnimap-transform-headers ()
191   (goto-char (point-min))
192   (let (article bytes lines size string)
193     (block nil
194       (while (not (eobp))
195         (while (not (looking-at "\\* [0-9]+ FETCH.+?UID \\([0-9]+\\)"))
196           (delete-region (point) (progn (forward-line 1) (point)))
197           (when (eobp)
198             (return)))
199         (setq article (match-string 1))
200         ;; Unfold quoted {number} strings.
201         (while (re-search-forward "[^]][ (]{\\([0-9]+\\)}\r?\n"
202                                   (1+ (line-end-position)) t)
203           (setq size (string-to-number (match-string 1)))
204           (delete-region (+ (match-beginning 0) 2) (point))
205           (setq string (buffer-substring (point) (+ (point) size)))
206           (delete-region (point) (+ (point) size))
207           (insert (format "%S" string)))
208         (setq bytes (nnimap-get-length)
209               lines nil)
210         (beginning-of-line)
211         (setq size
212               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
213                                       (line-end-position)
214                                       t)
215                    (match-string 1)))
216         (beginning-of-line)
217         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
218           (let ((structure (ignore-errors
219                              (read (current-buffer)))))
220             (while (and (consp structure)
221                         (not (atom (car structure))))
222               (setq structure (car structure)))
223             (setq lines (if (and
224                              (stringp (car structure))
225                              (equal (upcase (nth 0 structure)) "MESSAGE")
226                              (equal (upcase (nth 1 structure)) "RFC822"))
227                             (nth 9 structure)
228                           (nth 7 structure)))))
229         (delete-region (line-beginning-position) (line-end-position))
230         (insert (format "211 %s Article retrieved." article))
231         (forward-line 1)
232         (when size
233           (insert (format "Chars: %s\n" size)))
234         (when lines
235           (insert (format "Lines: %s\n" lines)))
236         (unless (re-search-forward "^\r$" nil t)
237           (goto-char (point-max)))
238         (delete-region (line-beginning-position) (line-end-position))
239         (insert ".")
240         (forward-line 1)))))
241
242 (defun nnimap-unfold-quoted-lines ()
243   ;; Unfold quoted {number} strings.
244   (let (size string)
245     (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
246       (setq size (string-to-number (match-string 1)))
247       (delete-region (1+ (match-beginning 0)) (point))
248       (setq string (buffer-substring (point) (+ (point) size)))
249       (delete-region (point) (+ (point) size))
250       (insert (format "%S" string)))))
251
252 (defun nnimap-get-length ()
253   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
254        (string-to-number (match-string 1))))
255
256 (defun nnimap-article-ranges (ranges)
257   (let (result)
258     (cond
259      ((numberp ranges)
260       (number-to-string ranges))
261      ((numberp (cdr ranges))
262       (format "%d:%d" (car ranges) (cdr ranges)))
263      (t
264       (dolist (elem ranges)
265         (push
266          (if (consp elem)
267              (format "%d:%d" (car elem) (cdr elem))
268            (number-to-string elem))
269          result))
270       (mapconcat #'identity (nreverse result) ",")))))
271
272 (deffoo nnimap-open-server (server &optional defs)
273   (if (nnimap-server-opened server)
274       t
275     (unless (assq 'nnimap-address defs)
276       (setq defs (append defs (list (list 'nnimap-address server)))))
277     (nnoo-change-server 'nnimap server defs)
278     (or (nnimap-find-connection nntp-server-buffer)
279         (nnimap-open-connection nntp-server-buffer))))
280
281 (defun nnimap-make-process-buffer (buffer)
282   (with-current-buffer
283       (generate-new-buffer (format "*nnimap %s %s %s*"
284                                    nnimap-address nnimap-server-port
285                                    (gnus-buffer-exists-p buffer)))
286     (mm-disable-multibyte)
287     (buffer-disable-undo)
288     (gnus-add-buffer)
289     (set (make-local-variable 'after-change-functions) nil)
290     (set (make-local-variable 'nnimap-object)
291          (make-nnimap :server (nnoo-current-server 'nnimap)
292                       :initial-resync 0))
293     (push (list buffer (current-buffer)) nnimap-connection-alist)
294     (push (current-buffer) nnimap-process-buffers)
295     (current-buffer)))
296
297 (defun nnimap-credentials (address ports user)
298   (let* ((auth-source-creation-prompts
299           '((user  . "IMAP user at %h: ")
300             (secret . "IMAP password for %u@%h: ")))
301          (found (nth 0 (auth-source-search :max 1
302                                            :host address
303                                            :port ports
304                                            :user user
305                                            :require '(:user :secret)
306                                            :create t))))
307     (if found
308         (list (plist-get found :user)
309               (let ((secret (plist-get found :secret)))
310                 (if (functionp secret)
311                     (funcall secret)
312                   secret))
313               (plist-get found :save-function))
314       nil)))
315
316 (defun nnimap-keepalive ()
317   (let ((now (current-time)))
318     (dolist (buffer nnimap-process-buffers)
319       (when (buffer-name buffer)
320         (with-current-buffer buffer
321           (when (and nnimap-object
322                      (nnimap-last-command-time nnimap-object)
323                      (> (gnus-float-time
324                          (time-subtract
325                           now
326                           (nnimap-last-command-time nnimap-object)))
327                         ;; More than five minutes since the last command.
328                         (* 5 60)))
329             (nnimap-send-command "NOOP")))))))
330
331 (defun nnimap-open-connection (buffer)
332   ;; Be backwards-compatible -- the earlier value of nnimap-stream was
333   ;; `ssl' when nnimap-server-port was nil.  Sort of.
334   (when (and nnimap-server-port
335              (eq nnimap-stream 'undecided))
336     (setq nnimap-stream 'ssl))
337   (let ((stream
338          (if (eq nnimap-stream 'undecided)
339              (loop for type in '(ssl network)
340                    for stream = (let ((nnimap-stream type))
341                                   (nnimap-open-connection-1 buffer))
342                    while (eq stream 'no-connect)
343                    finally (return stream))
344            (nnimap-open-connection-1 buffer))))
345     (if (eq stream 'no-connect)
346         nil
347       stream)))
348
349 (defun nnimap-map-port (port)
350   (if (equal port "imaps")
351       "993"
352     port))
353
354 (defun nnimap-open-connection-1 (buffer)
355   (unless nnimap-keepalive-timer
356     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
357                                               'nnimap-keepalive)))
358   (with-current-buffer (nnimap-make-process-buffer buffer)
359     (let* ((coding-system-for-read 'binary)
360            (coding-system-for-write 'binary)
361            (ports
362             (cond
363              ((memq nnimap-stream '(network plain starttls))
364               (nnheader-message 7 "Opening connection to %s..."
365                                 nnimap-address)
366               '("imap" "143"))
367              ((eq nnimap-stream 'shell)
368               (nnheader-message 7 "Opening connection to %s via shell..."
369                                 nnimap-address)
370               '("imap"))
371              ((memq nnimap-stream '(ssl tls))
372               (nnheader-message 7 "Opening connection to %s via tls..."
373                                 nnimap-address)
374               '("imaps" "imap" "993" "143"))
375              (t
376               (error "Unknown stream type: %s" nnimap-stream))))
377            login-result credentials)
378       (when nnimap-server-port
379         (push nnimap-server-port ports))
380       (let* ((stream-list
381               (open-protocol-stream
382                "*nnimap*" (current-buffer) nnimap-address
383                (nnimap-map-port (car ports))
384                :type nnimap-stream
385                :return-list t
386                :shell-command nnimap-shell-program
387                :capability-command "1 CAPABILITY\r\n"
388                :end-of-command "\r\n"
389                :success " OK "
390                :starttls-function
391                (lambda (capabilities)
392                  (when (gnus-string-match-p "STARTTLS" capabilities)
393                    "1 STARTTLS\r\n"))))
394              (stream (car stream-list))
395              (props (cdr stream-list))
396              (greeting (plist-get props :greeting))
397              (capabilities (plist-get props :capabilities))
398              (stream-type (plist-get props :type)))
399         (when (and stream (not (memq (process-status stream) '(open run))))
400           (setq stream nil))
401
402         (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
403                    (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
404                    (eq (process-type stream) 'network))
405           ;; Use TCP-keepalive so that connections that pass through a NAT
406           ;; router don't hang when left idle.
407           (set-network-process-option stream :keepalive t))
408
409         (setf (nnimap-process nnimap-object) stream)
410         (setf (nnimap-stream-type nnimap-object) stream-type)
411         (if (not stream)
412             (progn
413               (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
414                                nnimap-address (car ports) nnimap-stream)
415               'no-connect)
416           (gnus-set-process-query-on-exit-flag stream nil)
417           (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
418               (nnheader-report 'nnimap "%s" greeting)
419             ;; Store the greeting (for debugging purposes).
420             (setf (nnimap-greeting nnimap-object) greeting)
421             (setf (nnimap-capabilities nnimap-object)
422                   (mapcar #'upcase
423                           (split-string capabilities)))
424             (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
425               (if (not (setq credentials
426                              (if (eq nnimap-authenticator 'anonymous)
427                                  (list "anonymous"
428                                        (message-make-address))
429                                ;; Look for the credentials based on
430                                ;; the virtual server name and the address
431                                (nnimap-credentials
432                                 (gnus-delete-duplicates
433                                  (list
434                                   nnimap-address
435                                   (nnoo-current-server 'nnimap)))
436                                 ports
437                                 nnimap-user))))
438                   (setq nnimap-object nil)
439                 (let ((nnimap-inhibit-logging t))
440                   (setq login-result
441                         (nnimap-login (car credentials) (cadr credentials))))
442                 (if (car login-result)
443                     (progn
444                       ;; Save the credentials if a save function exists
445                       ;; (such a function will only be passed if a new
446                       ;; token was created).
447                       (when (functionp (nth 2 credentials))
448                         (funcall (nth 2 credentials)))
449                       ;; See if CAPABILITY is set as part of login
450                       ;; response.
451                       (dolist (response (cddr login-result))
452                         (when (string= "CAPABILITY" (upcase (car response)))
453                           (setf (nnimap-capabilities nnimap-object)
454                                 (mapcar #'upcase (cdr response))))))
455                   ;; If the login failed, then forget the credentials
456                   ;; that are now possibly cached.
457                   (dolist (host (list (nnoo-current-server 'nnimap)
458                                       nnimap-address))
459                     (dolist (port ports)
460                       (auth-source-forget+ :host host :port port)))
461                   (delete-process (nnimap-process nnimap-object))
462                   (setq nnimap-object nil))))
463             (when nnimap-object
464               (when (nnimap-capability "QRESYNC")
465                 (nnimap-command "ENABLE QRESYNC"))
466               (nnimap-process nnimap-object))))))))
467
468 (autoload 'rfc2104-hash "rfc2104")
469
470 (defun nnimap-login (user password)
471   (cond
472    ;; Prefer plain LOGIN if it's enabled (since it requires fewer
473    ;; round trips than CRAM-MD5, and it's less likely to be buggy),
474    ;; and we're using an encrypted connection.
475    ((and (not (nnimap-capability "LOGINDISABLED"))
476          (eq (nnimap-stream-type nnimap-object) 'tls))
477     (nnimap-command "LOGIN %S %S" user password))
478    ((nnimap-capability "AUTH=CRAM-MD5")
479     (erase-buffer)
480     (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
481           (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
482       (process-send-string
483        (get-buffer-process (current-buffer))
484        (concat
485         (base64-encode-string
486          (concat user " "
487                  (rfc2104-hash 'md5 64 16 password
488                                (base64-decode-string challenge))))
489         "\r\n"))
490       (nnimap-wait-for-response sequence)))
491    ((not (nnimap-capability "LOGINDISABLED"))
492     (nnimap-command "LOGIN %S %S" user password))
493    ((nnimap-capability "AUTH=PLAIN")
494     (nnimap-command
495      "AUTHENTICATE PLAIN %s"
496      (base64-encode-string
497       (format "\000%s\000%s"
498               (nnimap-quote-specials user)
499               (nnimap-quote-specials password)))))))
500
501 (defun nnimap-quote-specials (string)
502   (with-temp-buffer
503     (insert string)
504     (goto-char (point-min))
505     (while (re-search-forward "[\\\"]" nil t)
506       (forward-char -1)
507       (insert "\\")
508       (forward-char 1))
509     (buffer-string)))
510
511 (defun nnimap-find-parameter (parameter elems)
512   (let (result)
513     (dolist (elem elems)
514       (cond
515        ((equal (car elem) parameter)
516         (setq result (cdr elem)))
517        ((and (equal (car elem) "OK")
518              (consp (cadr elem))
519              (equal (caadr elem) parameter))
520         (setq result (cdr (cadr elem))))))
521     result))
522
523 (deffoo nnimap-close-server (&optional server)
524   (when (nnoo-change-server 'nnimap server nil)
525     (ignore-errors
526       (delete-process (get-buffer-process (nnimap-buffer))))
527     (nnoo-close-server 'nnimap server)
528     t))
529
530 (deffoo nnimap-request-close ()
531   t)
532
533 (deffoo nnimap-server-opened (&optional server)
534   (and (nnoo-current-server-p 'nnimap server)
535        nntp-server-buffer
536        (gnus-buffer-live-p nntp-server-buffer)
537        (nnimap-find-connection nntp-server-buffer)))
538
539 (deffoo nnimap-status-message (&optional server)
540   nnimap-status-string)
541
542 (deffoo nnimap-request-article (article &optional group server to-buffer)
543   (when group
544     (setq group (nnimap-decode-gnus-group group)))
545   (with-current-buffer nntp-server-buffer
546     (let ((result (nnimap-possibly-change-group group server))
547           parts structure)
548       (when (stringp article)
549         (setq article (nnimap-find-article-by-message-id group article)))
550       (when (and result
551                  article)
552         (erase-buffer)
553         (with-current-buffer (nnimap-buffer)
554           (erase-buffer)
555           (when nnimap-fetch-partial-articles
556             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
557             (goto-char (point-min))
558             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
559               (setq structure (ignore-errors
560                                 (let ((start (point)))
561                                   (forward-sexp 1)
562                                   (downcase-region start (point))
563                                   (goto-char start)
564                                   (read (current-buffer))))
565                     parts (nnimap-find-wanted-parts structure))))
566           (when (if parts
567                     (nnimap-get-partial-article article parts structure)
568                   (nnimap-get-whole-article article))
569             (let ((buffer (current-buffer)))
570               (with-current-buffer (or to-buffer nntp-server-buffer)
571                 (nnheader-insert-buffer-substring buffer)
572                 (nnheader-ms-strip-cr)))
573             (cons group article)))))))
574
575 (deffoo nnimap-request-head (article &optional group server to-buffer)
576   (when group
577     (setq group (nnimap-decode-gnus-group group)))
578   (when (nnimap-possibly-change-group group server)
579     (with-current-buffer (nnimap-buffer)
580       (when (stringp article)
581         (setq article (nnimap-find-article-by-message-id group article)))
582       (if (null article)
583           nil
584         (nnimap-get-whole-article
585          article (format "UID FETCH %%d %s"
586                          (nnimap-header-parameters)))
587         (let ((buffer (current-buffer)))
588           (with-current-buffer (or to-buffer nntp-server-buffer)
589             (erase-buffer)
590             (insert-buffer-substring buffer)
591             (nnheader-ms-strip-cr)
592             (cons group article)))))))
593
594 (defun nnimap-get-whole-article (article &optional command)
595   (let ((result
596          (nnimap-command
597           (or command
598               (if (nnimap-ver4-p)
599                   "UID FETCH %d BODY.PEEK[]"
600                 "UID FETCH %d RFC822.PEEK"))
601           article)))
602     ;; Check that we really got an article.
603     (goto-char (point-min))
604     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
605       (setq result nil))
606     (when result
607       ;; Remove any data that may have arrived before the FETCH data.
608       (beginning-of-line)
609       (unless (bobp)
610         (delete-region (point-min) (point)))
611       (let ((bytes (nnimap-get-length)))
612         (delete-region (line-beginning-position)
613                        (progn (forward-line 1) (point)))
614         (goto-char (+ (point) bytes))
615         (delete-region (point) (point-max)))
616       t)))
617
618 (defun nnimap-capability (capability)
619   (member capability (nnimap-capabilities nnimap-object)))
620
621 (defun nnimap-ver4-p ()
622   (nnimap-capability "IMAP4REV1"))
623
624 (defun nnimap-get-partial-article (article parts structure)
625   (let ((result
626          (nnimap-command
627           "UID FETCH %d (%s %s)"
628           article
629           (if (nnimap-ver4-p)
630               "BODY.PEEK[HEADER]"
631             "RFC822.HEADER")
632           (if (nnimap-ver4-p)
633               (mapconcat (lambda (part)
634                            (format "BODY.PEEK[%s]" part))
635                          parts " ")
636             (mapconcat (lambda (part)
637                          (format "RFC822.PEEK[%s]" part))
638                        parts " ")))))
639     (when result
640       (nnimap-convert-partial-article structure))))
641
642 (defun nnimap-convert-partial-article (structure)
643   ;; First just skip past the headers.
644   (goto-char (point-min))
645   (let ((bytes (nnimap-get-length))
646         id parts)
647     ;; Delete "FETCH" line.
648     (delete-region (line-beginning-position)
649                    (progn (forward-line 1) (point)))
650     (goto-char (+ (point) bytes))
651     ;; Collect all the body parts.
652     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
653       (setq id (match-string 1)
654             bytes (or (nnimap-get-length) 0))
655       (beginning-of-line)
656       (delete-region (point) (progn (forward-line 1) (point)))
657       (push (list id (buffer-substring (point) (+ (point) bytes)))
658             parts)
659       (delete-region (point) (+ (point) bytes)))
660     ;; Delete trailing junk.
661     (delete-region (point) (point-max))
662     ;; Now insert all the parts again where they fit in the structure.
663     (nnimap-insert-partial-structure structure parts)
664     t))
665
666 (defun nnimap-insert-partial-structure (structure parts &optional subp)
667   (let (type boundary)
668     (let ((bstruc structure))
669       (while (consp (car bstruc))
670         (pop bstruc))
671       (setq type (car bstruc))
672       (setq bstruc (car (cdr bstruc)))
673       (let ((has-boundary (member "boundary" bstruc)))
674         (when has-boundary
675           (setq boundary (cadr has-boundary)))))
676     (when subp
677       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
678                       (downcase type) boundary)))
679     (while (not (stringp (car structure)))
680       (insert "\n--" boundary "\n")
681       (if (consp (caar structure))
682           (nnimap-insert-partial-structure (pop structure) parts t)
683         (let ((bit (pop structure)))
684           (insert (format "Content-type: %s/%s"
685                           (downcase (nth 0 bit))
686                           (downcase (nth 1 bit))))
687           (if (member-ignore-case "CHARSET" (nth 2 bit))
688               (insert (format
689                        "; charset=%S\n"
690                        (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
691             (insert "\n"))
692           (insert (format "Content-transfer-encoding: %s\n"
693                           (nth 5 bit)))
694           (insert "\n")
695           (when (assoc (nth 9 bit) parts)
696             (insert (cadr (assoc (nth 9 bit) parts)))))))
697     (insert "\n--" boundary "--\n")))
698
699 (defun nnimap-find-wanted-parts (structure)
700   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
701
702 (defun nnimap-find-wanted-parts-1 (structure prefix)
703   (let ((num 1)
704         parts)
705     (while (consp (car structure))
706       (let ((sub (pop structure)))
707         (if (consp (car sub))
708             (push (nnimap-find-wanted-parts-1
709                    sub (if (string= prefix "")
710                            (number-to-string num)
711                          (format "%s.%s" prefix num)))
712                   parts)
713           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
714                 (id (if (string= prefix "")
715                         (number-to-string num)
716                       (format "%s.%s" prefix num))))
717             (setcar (nthcdr 9 sub) id)
718             (when (if (eq nnimap-fetch-partial-articles t)
719                       (equal id "1")
720                     (string-match nnimap-fetch-partial-articles type))
721               (push id parts))))
722         (incf num)))
723     (nreverse parts)))
724
725 (defun nnimap-decode-gnus-group (group)
726   (decode-coding-string group 'utf-8))
727
728 (deffoo nnimap-request-group (group &optional server dont-check info)
729   (setq group (nnimap-decode-gnus-group group))
730   (let ((result (nnimap-possibly-change-group
731                  ;; Don't SELECT the group if we're going to select it
732                  ;; later, anyway.
733                  (if (and (not dont-check)
734                           (assoc group nnimap-current-infos))
735                      nil
736                    group)
737                  server))
738         articles active marks high low)
739     (with-current-buffer nntp-server-buffer
740       (when result
741         (if (and dont-check
742                  (setq active (nth 2 (assoc group nnimap-current-infos))))
743             (insert (format "211 %d %d %d %S\n"
744                             (- (cdr active) (car active))
745                             (car active)
746                             (cdr active)
747                             group))
748           (with-current-buffer (nnimap-buffer)
749             (erase-buffer)
750             (let ((group-sequence
751                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
752                   (flag-sequence
753                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
754               (setf (nnimap-group nnimap-object) group)
755               (nnimap-wait-for-response flag-sequence)
756               (setq marks
757                     (nnimap-flags-to-marks
758                      (nnimap-parse-flags
759                       (list (list group-sequence flag-sequence
760                                   1 group "SELECT")))))
761               (when (and info
762                          marks)
763                 (nnimap-update-infos marks (list info))
764                 (nnimap-store-info info (gnus-active (gnus-info-group info))))
765               (goto-char (point-max))
766               (let ((uidnext (nth 5 (car marks))))
767                 (setq high (or (if uidnext
768                                    (1- uidnext)
769                                  (nth 3 (car marks)))
770                                0)
771                       low (or (nth 4 (car marks)) uidnext 1)))))
772           (erase-buffer)
773           (insert
774            (format
775             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
776         t))))
777
778 (deffoo nnimap-request-create-group (group &optional server args)
779   (setq group (nnimap-decode-gnus-group group))
780   (when (nnimap-possibly-change-group nil server)
781     (with-current-buffer (nnimap-buffer)
782       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
783
784 (deffoo nnimap-request-delete-group (group &optional force server)
785   (setq group (nnimap-decode-gnus-group group))
786   (when (nnimap-possibly-change-group nil server)
787     (with-current-buffer (nnimap-buffer)
788       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
789
790 (deffoo nnimap-request-rename-group (group new-name &optional server)
791   (setq group (nnimap-decode-gnus-group group))
792   (when (nnimap-possibly-change-group nil server)
793     (with-current-buffer (nnimap-buffer)
794       (nnimap-unselect-group)
795       (car (nnimap-command "RENAME %S %S"
796                            (utf7-encode group t) (utf7-encode new-name t))))))
797
798 (defun nnimap-unselect-group ()
799   ;; Make sure we don't have this group open read/write by asking
800   ;; to examine a mailbox that doesn't exist.  This seems to be
801   ;; the only way that allows us to reliably go back to unselected
802   ;; state on Courier.
803   (nnimap-command "EXAMINE DOES.NOT.EXIST"))
804
805 (deffoo nnimap-request-expunge-group (group &optional server)
806   (setq group (nnimap-decode-gnus-group group))
807   (when (nnimap-possibly-change-group group server)
808     (with-current-buffer (nnimap-buffer)
809       (car (nnimap-command "EXPUNGE")))))
810
811 (defun nnimap-get-flags (spec)
812   (let ((articles nil)
813         elems end)
814     (with-current-buffer (nnimap-buffer)
815       (erase-buffer)
816       (nnimap-wait-for-response (nnimap-send-command
817                                  "UID FETCH %s FLAGS" spec))
818       (setq end (point))
819       (subst-char-in-region (point-min) (point-max)
820                             ?\\ ?% t)
821       (goto-char (point-min))
822       (while (search-forward " FETCH " end t)
823         (setq elems (read (current-buffer)))
824         (push (cons (cadr (memq 'UID elems))
825                     (cadr (memq 'FLAGS elems)))
826               articles)))
827     (nreverse articles)))
828
829 (deffoo nnimap-close-group (group &optional server)
830   t)
831
832 (deffoo nnimap-request-move-article (article group server accept-form
833                                              &optional last internal-move-group)
834   (setq group (nnimap-decode-gnus-group group))
835   (with-temp-buffer
836     (mm-disable-multibyte)
837     (when (funcall (if internal-move-group
838                        'nnimap-request-head
839                      'nnimap-request-article)
840                    article group server (current-buffer))
841       ;; If the move is internal (on the same server), just do it the easy
842       ;; way.
843       (let ((message-id (message-field-value "message-id")))
844         (if internal-move-group
845             (let ((result
846                    (with-current-buffer (nnimap-buffer)
847                      (nnimap-command "UID COPY %d %S"
848                                      article
849                                      (utf7-encode internal-move-group t)))))
850               (when (car result)
851                 (nnimap-delete-article article)
852                 (cons internal-move-group
853                       (or (nnimap-find-uid-response "COPYUID" (cadr result))
854                           (nnimap-find-article-by-message-id
855                            internal-move-group message-id)))))
856           ;; Move the article to a different method.
857           (let ((result (eval accept-form)))
858             (when result
859               (nnimap-delete-article article)
860               result)))))))
861
862 (deffoo nnimap-request-expire-articles (articles group &optional server force)
863   (setq group (nnimap-decode-gnus-group group))
864   (cond
865    ((null articles)
866     nil)
867    ((not (nnimap-possibly-change-group group server))
868     articles)
869    ((and force
870          (eq nnmail-expiry-target 'delete))
871     (unless (nnimap-delete-article (gnus-compress-sequence articles))
872       (nnheader-message 7 "Article marked for deletion, but not expunged."))
873     nil)
874    (t
875     (let ((deletable-articles
876            (if (or force
877                    (eq nnmail-expiry-wait 'immediate))
878                articles
879              (gnus-sorted-intersection
880               articles
881               (nnimap-find-expired-articles group)))))
882       (if (null deletable-articles)
883           articles
884         (if (eq nnmail-expiry-target 'delete)
885             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
886           (setq deletable-articles
887                 (nnimap-process-expiry-targets
888                  deletable-articles group server)))
889         ;; Return the articles we didn't delete.
890         (gnus-sorted-complement articles deletable-articles))))))
891
892 (defun nnimap-process-expiry-targets (articles group server)
893   (let ((deleted-articles nil))
894     (cond
895      ;; shortcut further processing if we're going to delete the articles
896      ((eq nnmail-expiry-target 'delete)
897       (setq deleted-articles articles)
898       t)
899      ;; or just move them to another folder on the same IMAP server
900      ((and (not (functionp nnmail-expiry-target))
901            (gnus-server-equal (gnus-group-method nnmail-expiry-target)
902                               (gnus-server-to-method
903                                (format "nnimap:%s" server))))
904       (and (nnimap-possibly-change-group group server)
905            (with-current-buffer (nnimap-buffer)
906              (nnheader-message 7 "Expiring articles from %s: %s" group articles)
907              (nnimap-command
908               "UID COPY %s %S"
909               (nnimap-article-ranges (gnus-compress-sequence articles))
910               (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
911              (setq deleted-articles articles)))
912       t)
913      (t
914       (dolist (article articles)
915         (let ((target nnmail-expiry-target))
916           (with-temp-buffer
917             (mm-disable-multibyte)
918             (when (nnimap-request-article article group server (current-buffer))
919               (when (functionp target)
920                 (setq target (funcall target group)))
921               (if (and target
922                        (not (eq target 'delete)))
923                   (if (or (gnus-request-group target t)
924                           (gnus-request-create-group target))
925                       (progn
926                         (nnmail-expiry-target-group target group)
927                         (nnheader-message 7 "Expiring article %s:%d to %s"
928                                           group article target))
929                     (setq target nil))
930                 (nnheader-message 7 "Expiring article %s:%d" group article))
931               (when target
932                 (push article deleted-articles))))))))
933     ;; Change back to the current group again.
934     (nnimap-possibly-change-group group server)
935     (setq deleted-articles (nreverse deleted-articles))
936     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
937     deleted-articles))
938
939 (defun nnimap-find-expired-articles (group)
940   (let ((cutoff (nnmail-expired-article-p group nil nil)))
941     (with-current-buffer (nnimap-buffer)
942       (let ((result
943              (nnimap-command
944               "UID SEARCH SENTBEFORE %s"
945               (format-time-string
946                (format "%%d-%s-%%Y"
947                        (upcase
948                         (car (rassoc (nth 4 (decode-time cutoff))
949                                      parse-time-months))))
950                cutoff))))
951         (and (car result)
952              (delete 0 (mapcar #'string-to-number
953                                (cdr (assoc "SEARCH" (cdr result))))))))))
954
955
956 (defun nnimap-find-article-by-message-id (group message-id)
957   (with-current-buffer (nnimap-buffer)
958     (erase-buffer)
959     (unless (equal group (nnimap-group nnimap-object))
960       (setf (nnimap-group nnimap-object) nil)
961       (setf (nnimap-examined nnimap-object) group)
962       (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
963     (let ((sequence
964            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
965           article result)
966       (setq result (nnimap-wait-for-response sequence))
967       (when (and result
968                  (car (setq result (nnimap-parse-response))))
969         ;; Select the last instance of the message in the group.
970         (and (setq article
971                    (car (last (cdr (assoc "SEARCH" (cdr result))))))
972              (string-to-number article))))))
973
974 (defun nnimap-delete-article (articles)
975   (with-current-buffer (nnimap-buffer)
976     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
977                     (nnimap-article-ranges articles))
978     (cond
979      ((nnimap-capability "UIDPLUS")
980       (nnimap-command "UID EXPUNGE %s"
981                       (nnimap-article-ranges articles))
982       t)
983      (nnimap-expunge
984       (nnimap-command "EXPUNGE")
985       t)
986      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
987                                 "server doesn't support UIDPLUS, so we won't "
988                                 "delete this article now"))))))
989
990 (deffoo nnimap-request-scan (&optional group server)
991   (when group
992     (setq group (nnimap-decode-gnus-group group)))
993   (when (and (nnimap-possibly-change-group nil server)
994              nnimap-inbox
995              nnimap-split-methods)
996     (nnheader-message 7 "nnimap %s splitting mail..." server)
997     (nnimap-split-incoming-mail)
998     (nnheader-message 7 "nnimap %s splitting mail...done" server)))
999
1000 (defun nnimap-marks-to-flags (marks)
1001   (let (flags flag)
1002     (dolist (mark marks)
1003       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1004         (push flag flags)))
1005     flags))
1006
1007 (deffoo nnimap-request-update-group-status (group status &optional server)
1008   (setq group (nnimap-decode-gnus-group group))
1009   (when (nnimap-possibly-change-group nil server)
1010     (let ((command (assoc
1011                     status
1012                     '((subscribe "SUBSCRIBE")
1013                       (unsubscribe "UNSUBSCRIBE")))))
1014       (when command
1015         (with-current-buffer (nnimap-buffer)
1016           (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1017
1018 (deffoo nnimap-request-set-mark (group actions &optional server)
1019   (setq group (nnimap-decode-gnus-group group))
1020   (when (nnimap-possibly-change-group group server)
1021     (let (sequence)
1022       (with-current-buffer (nnimap-buffer)
1023         (erase-buffer)
1024         ;; Just send all the STORE commands without waiting for
1025         ;; response.  If they're successful, they're successful.
1026         (dolist (action actions)
1027           (destructuring-bind (range action marks) action
1028             (let ((flags (nnimap-marks-to-flags marks)))
1029               (when flags
1030                 (setq sequence (nnimap-send-command
1031                                 "UID STORE %s %sFLAGS.SILENT (%s)"
1032                                 (nnimap-article-ranges range)
1033                                 (cond
1034                                  ((eq action 'del) "-")
1035                                  ((eq action 'add) "+")
1036                                  ((eq action 'set) ""))
1037                                 (mapconcat #'identity flags " ")))))))
1038         ;; Wait for the last command to complete to avoid later
1039         ;; synchronization problems with the stream.
1040         (when sequence
1041           (nnimap-wait-for-response sequence))))))
1042
1043 (deffoo nnimap-request-accept-article (group &optional server last)
1044   (setq group (nnimap-decode-gnus-group group))
1045   (when (nnimap-possibly-change-group nil server)
1046     (nnmail-check-syntax)
1047     (let ((message-id (message-field-value "message-id"))
1048           sequence message)
1049       (nnimap-add-cr)
1050       (setq message (buffer-substring-no-properties (point-min) (point-max)))
1051       (with-current-buffer (nnimap-buffer)
1052         (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1053                                 message))
1054           ;; If we have this group open read-only, then unselect it
1055           ;; before appending to it.
1056           (when (equal (nnimap-examined nnimap-object) group)
1057             (nnimap-unselect-group))
1058           (erase-buffer)
1059           (setq sequence (nnimap-send-command
1060                           "APPEND %S {%d}" (utf7-encode group t)
1061                           (length message)))
1062           (unless nnimap-streaming
1063             (nnimap-wait-for-connection "^[+]"))
1064           (process-send-string (get-buffer-process (current-buffer)) message)
1065           (process-send-string (get-buffer-process (current-buffer))
1066                                (if (nnimap-newlinep nnimap-object)
1067                                    "\n"
1068                                  "\r\n"))
1069           (let ((result (nnimap-get-response sequence)))
1070             (if (not (nnimap-ok-p result))
1071                 (progn
1072                   (nnheader-report 'nnimap "%s" result)
1073                   nil)
1074               (cons group
1075                     (or (nnimap-find-uid-response "APPENDUID" (car result))
1076                         (nnimap-find-article-by-message-id
1077                          group message-id))))))))))
1078
1079 (defun nnimap-process-quirk (greeting-match type data)
1080   (when (and (nnimap-greeting nnimap-object)
1081              (string-match greeting-match (nnimap-greeting nnimap-object))
1082              (eq type 'append)
1083              (string-match "\000" data))
1084     (let ((choice (gnus-multiple-choice
1085                    "Message contains NUL characters.  Delete, continue, abort? "
1086                    '((?d "Delete NUL characters")
1087                      (?c "Try to APPEND the message as is")
1088                      (?a "Abort")))))
1089       (cond
1090        ((eq choice ?a)
1091         (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1092        ((eq choice ?c)
1093         data)
1094        (t
1095         (with-temp-buffer
1096           (insert data)
1097           (goto-char (point-min))
1098           (while (search-forward "\000" nil t)
1099             (replace-match "" t t))
1100           (buffer-string)))))))
1101
1102 (defun nnimap-ok-p (value)
1103   (and (consp value)
1104        (consp (car value))
1105        (equal (caar value) "OK")))
1106
1107 (defun nnimap-find-uid-response (name list)
1108   (let ((result (car (last (nnimap-find-response-element name list)))))
1109     (and result
1110          (string-to-number result))))
1111
1112 (defun nnimap-find-response-element (name list)
1113   (let (result)
1114     (dolist (elem list)
1115       (when (and (consp elem)
1116                  (equal name (car elem)))
1117         (setq result elem)))
1118     result))
1119
1120 (deffoo nnimap-request-replace-article (article group buffer)
1121   (setq group (nnimap-decode-gnus-group group))
1122   (let (group-art)
1123     (when (and (nnimap-possibly-change-group group nil)
1124                ;; Put the article into the group.
1125                (with-current-buffer buffer
1126                  (setq group-art
1127                        (nnimap-request-accept-article group nil t))))
1128       (nnimap-delete-article (list article))
1129       ;; Return the new article number.
1130       (cdr group-art))))
1131
1132 (defun nnimap-add-cr ()
1133   (goto-char (point-min))
1134   (while (re-search-forward "\r?\n" nil t)
1135     (replace-match "\r\n" t t)))
1136
1137 (defun nnimap-get-groups ()
1138   (erase-buffer)
1139   (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1140         groups)
1141     (nnimap-wait-for-response sequence)
1142     (subst-char-in-region (point-min) (point-max)
1143                           ?\\ ?% t)
1144     (goto-char (point-min))
1145     (nnimap-unfold-quoted-lines)
1146     (goto-char (point-min))
1147     (while (search-forward "* LIST " nil t)
1148       (let ((flags (read (current-buffer)))
1149             (separator (read (current-buffer)))
1150             (group (read (current-buffer))))
1151         (unless (member '%NoSelect flags)
1152           (push (utf7-decode (if (stringp group)
1153                                  group
1154                                (format "%s" group)) t)
1155                 groups))))
1156     (nreverse groups)))
1157
1158 (deffoo nnimap-request-list (&optional server)
1159   (when (nnimap-possibly-change-group nil server)
1160     (with-current-buffer nntp-server-buffer
1161       (erase-buffer)
1162       (let ((groups
1163              (with-current-buffer (nnimap-buffer)
1164                (nnimap-get-groups)))
1165             sequences responses)
1166         (when groups
1167           (with-current-buffer (nnimap-buffer)
1168             (setf (nnimap-group nnimap-object) nil)
1169             (dolist (group groups)
1170               (setf (nnimap-examined nnimap-object) group)
1171               (push (list (nnimap-send-command "EXAMINE %S"
1172                                                (utf7-encode group t))
1173                           group)
1174                     sequences))
1175             (nnimap-wait-for-response (caar sequences))
1176             (setq responses
1177                   (nnimap-get-responses (mapcar #'car sequences))))
1178           (dolist (response responses)
1179             (let* ((sequence (car response))
1180                    (response (cadr response))
1181                    (group (cadr (assoc sequence sequences))))
1182               (when (and group
1183                          (equal (caar response) "OK"))
1184                 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1185                       highest exists)
1186                   (dolist (elem response)
1187                     (when (equal (cadr elem) "EXISTS")
1188                       (setq exists (string-to-number (car elem)))))
1189                   (when uidnext
1190                     (setq highest (1- (string-to-number (car uidnext)))))
1191                   (cond
1192                    ((null highest)
1193                     (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1194                    ((zerop exists)
1195                     ;; Empty group.
1196                     (insert (format "%S %d %d y\n"
1197                                     (utf7-decode group t)
1198                                     highest (1+ highest))))
1199                    (t
1200                     ;; Return the widest possible range.
1201                     (insert (format "%S %d 1 y\n" (utf7-decode group t)
1202                                     (or highest exists)))))))))
1203           t)))))
1204
1205 (deffoo nnimap-request-newgroups (date &optional server)
1206   (when (nnimap-possibly-change-group nil server)
1207     (with-current-buffer nntp-server-buffer
1208       (erase-buffer)
1209       (dolist (group (with-current-buffer (nnimap-buffer)
1210                        (nnimap-get-groups)))
1211         (unless (assoc group nnimap-current-infos)
1212           ;; Insert dummy numbers here -- they don't matter.
1213           (insert (format "%S 0 1 y\n" (utf7-encode group)))))
1214       t)))
1215
1216 (deffoo nnimap-retrieve-group-data-early (server infos)
1217   (when (and (nnimap-possibly-change-group nil server)
1218              infos)
1219     (with-current-buffer (nnimap-buffer)
1220       (erase-buffer)
1221       (setf (nnimap-group nnimap-object) nil)
1222       (setf (nnimap-initial-resync nnimap-object) 0)
1223       (let ((qresyncp (nnimap-capability "QRESYNC"))
1224             params groups sequences active uidvalidity modseq group)
1225         ;; Go through the infos and gather the data needed to know
1226         ;; what and how to request the data.
1227         (dolist (info infos)
1228           (setq params (gnus-info-params info)
1229                 group (nnimap-decode-gnus-group
1230                        (gnus-group-real-name (gnus-info-group info)))
1231                 active (cdr (assq 'active params))
1232                 uidvalidity (cdr (assq 'uidvalidity params))
1233                 modseq (cdr (assq 'modseq params)))
1234           (setf (nnimap-examined nnimap-object) group)
1235           (if (and qresyncp
1236                    uidvalidity
1237                    active
1238                    modseq)
1239               (push
1240                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1241                                           (utf7-encode group t)
1242                                           (nnimap-quirk "QRESYNC")
1243                                           uidvalidity modseq)
1244                      'qresync
1245                      nil group 'qresync)
1246                sequences)
1247             (let ((start
1248                    (if (and active uidvalidity)
1249                        ;; Fetch the last 100 flags.
1250                        (max 1 (- (cdr active) 100))
1251                      1))
1252                   (command
1253                    (if uidvalidity
1254                        "EXAMINE"
1255                      ;; If we don't have a UIDVALIDITY, then this is
1256                      ;; the first time we've seen the group, so we
1257                      ;; have to do a SELECT (which is slower than an
1258                      ;; examine), but will tell us whether the group
1259                      ;; is read-only or not.
1260                      "SELECT")))
1261               (setf (nnimap-initial-resync nnimap-object)
1262                     (1+ (nnimap-initial-resync nnimap-object)))
1263               (push (list (nnimap-send-command "%s %S" command
1264                                                (utf7-encode group t))
1265                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1266                           start group command)
1267                     sequences))))
1268         sequences))))
1269
1270 (defun nnimap-quirk (command)
1271   (let ((quirk (assoc command nnimap-quirks)))
1272     ;; If this server is of a type that matches a quirk, then return
1273     ;; the "quirked" command instead of the proper one.
1274     (if (or (null quirk)
1275             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1276         command
1277       (nth 2 quirk))))
1278
1279 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1280   (when (and sequences
1281              (nnimap-possibly-change-group nil server)
1282              ;; Check that the process is still alive.
1283              (get-buffer-process (nnimap-buffer))
1284              (memq (process-status (get-buffer-process (nnimap-buffer)))
1285                    '(open run)))
1286     (with-current-buffer (nnimap-buffer)
1287       ;; Wait for the final data to trickle in.
1288       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1289                                           (caar sequences)
1290                                         (cadar sequences))
1291                                       t)
1292         ;; Now we should have most of the data we need, no matter
1293         ;; whether we're QRESYNCING, fetching all the flags from
1294         ;; scratch, or just fetching the last 100 flags per group.
1295         (nnimap-update-infos (nnimap-flags-to-marks
1296                               (nnimap-parse-flags
1297                                (nreverse sequences)))
1298                              infos)
1299         ;; Finally, just return something resembling an active file in
1300         ;; the nntp buffer, so that the agent can save the info, too.
1301         (with-current-buffer nntp-server-buffer
1302           (erase-buffer)
1303           (dolist (info infos)
1304             (let* ((group (gnus-info-group info))
1305                    (active (gnus-active group)))
1306               (when active
1307                 (insert (format "%S %d %d y\n"
1308                                 (decode-coding-string
1309                                  (gnus-group-real-name group) 'utf-8)
1310                                 (cdr active)
1311                                 (car active)))))))))))
1312
1313 (defun nnimap-update-infos (flags infos)
1314   (dolist (info infos)
1315     (let* ((group (nnimap-decode-gnus-group
1316                    (gnus-group-real-name (gnus-info-group info))))
1317            (marks (cdr (assoc group flags))))
1318       (when marks
1319         (nnimap-update-info info marks)))))
1320
1321 (defun nnimap-update-info (info marks)
1322   (destructuring-bind (existing flags high low uidnext start-article
1323                                 permanent-flags uidvalidity
1324                                 vanished highestmodseq) marks
1325     (cond
1326      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1327      ;; completely empty groups.
1328      ((and (not existing)
1329            (not uidnext))
1330       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1331         (when active
1332           (gnus-set-active (gnus-info-group info) active))))
1333      ;; We have a mismatch between the old and new UIDVALIDITY
1334      ;; identifiers, so we have to re-request the group info (the next
1335      ;; time).  This virtually never happens.
1336      ((let ((old-uidvalidity
1337              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1338         (and old-uidvalidity
1339              (not (equal old-uidvalidity uidvalidity))
1340              (or (not start-article)
1341                  (> start-article 1))))
1342       (gnus-group-remove-parameter info 'uidvalidity)
1343       (gnus-group-remove-parameter info 'modseq))
1344      ;; We have the data needed to update.
1345      (t
1346       (let* ((group (gnus-info-group info))
1347              (completep (and start-article
1348                              (= start-article 1)))
1349              (active (or (gnus-active group)
1350                   &nb