Redo the charset handling for group names in nnimap.
[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   ;; 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)
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     (push (list buffer (current-buffer)) nnimap-connection-alist)
293     (push (current-buffer) nnimap-process-buffers)
294     (current-buffer)))
295
296 (defun nnimap-credentials (address ports user)
297   (let* ((auth-source-creation-prompts
298           '((user  . "IMAP user at %h: ")
299             (secret . "IMAP password for %u@%h: ")))
300          (found (nth 0 (auth-source-search :max 1
301                                            :host address
302                                            :port ports
303                                            :user user
304                                            :require '(:user :secret)
305                                            :create t))))
306     (if found
307         (list (plist-get found :user)
308               (let ((secret (plist-get found :secret)))
309                 (if (functionp secret)
310                     (funcall secret)
311                   secret))
312               (plist-get found :save-function))
313       nil)))
314
315 (defun nnimap-keepalive ()
316   (let ((now (current-time)))
317     (dolist (buffer nnimap-process-buffers)
318       (when (buffer-name buffer)
319         (with-current-buffer buffer
320           (when (and nnimap-object
321                      (nnimap-last-command-time nnimap-object)
322                      (> (gnus-float-time
323                          (time-subtract
324                           now
325                           (nnimap-last-command-time nnimap-object)))
326                         ;; More than five minutes since the last command.
327                         (* 5 60)))
328             (nnimap-send-command "NOOP")))))))
329
330 (defun nnimap-open-connection (buffer)
331   ;; Be backwards-compatible -- the earlier value of nnimap-stream was
332   ;; `ssl' when nnimap-server-port was nil.  Sort of.
333   (when (and nnimap-server-port
334              (eq nnimap-stream 'undecided))
335     (setq nnimap-stream 'ssl))
336   (let ((stream
337          (if (eq nnimap-stream 'undecided)
338              (loop for type in '(ssl network)
339                    for stream = (let ((nnimap-stream type))
340                                   (nnimap-open-connection-1 buffer))
341                    while (eq stream 'no-connect)
342                    finally (return stream))
343            (nnimap-open-connection-1 buffer))))
344     (if (eq stream 'no-connect)
345         nil
346       stream)))
347
348 (defun nnimap-open-connection-1 (buffer)
349   (unless nnimap-keepalive-timer
350     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
351                                               'nnimap-keepalive)))
352   (with-current-buffer (nnimap-make-process-buffer buffer)
353     (let* ((coding-system-for-read 'binary)
354            (coding-system-for-write 'binary)
355            (ports
356             (cond
357              ((memq nnimap-stream '(network plain starttls))
358               (nnheader-message 7 "Opening connection to %s..."
359                                 nnimap-address)
360               '("imap" "143"))
361              ((eq nnimap-stream 'shell)
362               (nnheader-message 7 "Opening connection to %s via shell..."
363                                 nnimap-address)
364               '("imap"))
365              ((memq nnimap-stream '(ssl tls))
366               (nnheader-message 7 "Opening connection to %s via tls..."
367                                 nnimap-address)
368               '("imaps" "imap" "993" "143"))
369              (t
370               (error "Unknown stream type: %s" nnimap-stream))))
371            login-result credentials)
372       (when nnimap-server-port
373         (push nnimap-server-port ports))
374       (let* ((stream-list
375               (open-protocol-stream
376                "*nnimap*" (current-buffer) nnimap-address (car ports)
377                :type nnimap-stream
378                :return-list t
379                :shell-command nnimap-shell-program
380                :capability-command "1 CAPABILITY\r\n"
381                :end-of-command "\r\n"
382                :success " OK "
383                :starttls-function
384                (lambda (capabilities)
385                  (when (gnus-string-match-p "STARTTLS" capabilities)
386                    "1 STARTTLS\r\n"))))
387              (stream (car stream-list))
388              (props (cdr stream-list))
389              (greeting (plist-get props :greeting))
390              (capabilities (plist-get props :capabilities))
391              (stream-type (plist-get props :type)))
392         (when (and stream (not (memq (process-status stream) '(open run))))
393           (setq stream nil))
394         (setf (nnimap-process nnimap-object) stream)
395         (setf (nnimap-stream-type nnimap-object) stream-type)
396         (if (not stream)
397             (progn
398               (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
399                                nnimap-address (car ports) nnimap-stream)
400               'no-connect)
401           (gnus-set-process-query-on-exit-flag stream nil)
402           (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
403               (nnheader-report 'nnimap "%s" greeting)
404             ;; Store the greeting (for debugging purposes).
405             (setf (nnimap-greeting nnimap-object) greeting)
406             (setf (nnimap-capabilities nnimap-object)
407                   (mapcar #'upcase
408                           (split-string capabilities)))
409             (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
410               (if (not (setq credentials
411                              (if (eq nnimap-authenticator 'anonymous)
412                                  (list "anonymous"
413                                        (message-make-address))
414                                ;; Look for the credentials based on
415                                ;; the virtual server name and the address
416                                (nnimap-credentials
417                                 (gnus-delete-duplicates
418                                  (list
419                                   nnimap-address
420                                   (nnoo-current-server 'nnimap)))
421                                 ports
422                                 nnimap-user))))
423                   (setq nnimap-object nil)
424                 (let ((nnimap-inhibit-logging t))
425                   (setq login-result
426                         (nnimap-login (car credentials) (cadr credentials))))
427                 (if (car login-result)
428                     (progn
429                       ;; Save the credentials if a save function exists
430                       ;; (such a function will only be passed if a new
431                       ;; token was created).
432                       (when (functionp (nth 2 credentials))
433                         (funcall (nth 2 credentials)))
434                       ;; See if CAPABILITY is set as part of login
435                       ;; response.
436                       (dolist (response (cddr login-result))
437                         (when (string= "CAPABILITY" (upcase (car response)))
438                           (setf (nnimap-capabilities nnimap-object)
439                                 (mapcar #'upcase (cdr response))))))
440                   ;; If the login failed, then forget the credentials
441                   ;; that are now possibly cached.
442                   (dolist (host (list (nnoo-current-server 'nnimap)
443                                       nnimap-address))
444                     (dolist (port ports)
445                       (auth-source-forget+ :host host :port port)))
446                   (delete-process (nnimap-process nnimap-object))
447                   (setq nnimap-object nil))))
448             (when nnimap-object
449               (when (nnimap-capability "QRESYNC")
450                 (nnimap-command "ENABLE QRESYNC"))
451               (nnimap-process nnimap-object))))))))
452
453 (autoload 'rfc2104-hash "rfc2104")
454
455 (defun nnimap-login (user password)
456   (cond
457    ;; Prefer plain LOGIN if it's enabled (since it requires fewer
458    ;; round trips than CRAM-MD5, and it's less likely to be buggy),
459    ;; and we're using an encrypted connection.
460    ((and (not (nnimap-capability "LOGINDISABLED"))
461          (eq (nnimap-stream-type nnimap-object) 'tls))
462     (nnimap-command "LOGIN %S %S" user password))
463    ((nnimap-capability "AUTH=CRAM-MD5")
464     (erase-buffer)
465     (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
466           (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
467       (process-send-string
468        (get-buffer-process (current-buffer))
469        (concat
470         (base64-encode-string
471          (concat user " "
472                  (rfc2104-hash 'md5 64 16 password
473                                (base64-decode-string challenge))))
474         "\r\n"))
475       (nnimap-wait-for-response sequence)))
476    ((not (nnimap-capability "LOGINDISABLED"))
477     (nnimap-command "LOGIN %S %S" user password))
478    ((nnimap-capability "AUTH=PLAIN")
479     (nnimap-command
480      "AUTHENTICATE PLAIN %s"
481      (base64-encode-string
482       (format "\000%s\000%s"
483               (nnimap-quote-specials user)
484               (nnimap-quote-specials password)))))))
485
486 (defun nnimap-quote-specials (string)
487   (with-temp-buffer
488     (insert string)
489     (goto-char (point-min))
490     (while (re-search-forward "[\\\"]" nil t)
491       (forward-char -1)
492       (insert "\\")
493       (forward-char 1))
494     (buffer-string)))
495
496 (defun nnimap-find-parameter (parameter elems)
497   (let (result)
498     (dolist (elem elems)
499       (cond
500        ((equal (car elem) parameter)
501         (setq result (cdr elem)))
502        ((and (equal (car elem) "OK")
503              (consp (cadr elem))
504              (equal (caadr elem) parameter))
505         (setq result (cdr (cadr elem))))))
506     result))
507
508 (deffoo nnimap-close-server (&optional server)
509   (when (nnoo-change-server 'nnimap server nil)
510     (ignore-errors
511       (delete-process (get-buffer-process (nnimap-buffer))))
512     (nnoo-close-server 'nnimap server)
513     t))
514
515 (deffoo nnimap-request-close ()
516   t)
517
518 (deffoo nnimap-server-opened (&optional server)
519   (and (nnoo-current-server-p 'nnimap server)
520        nntp-server-buffer
521        (gnus-buffer-live-p nntp-server-buffer)
522        (nnimap-find-connection nntp-server-buffer)))
523
524 (deffoo nnimap-status-message (&optional server)
525   nnimap-status-string)
526
527 (deffoo nnimap-request-article (article &optional group server to-buffer)
528   (when group
529     (setq group (nnimap-decode-gnus-group group)))
530   (with-current-buffer nntp-server-buffer
531     (let ((result (nnimap-possibly-change-group group server))
532           parts structure)
533       (when (stringp article)
534         (setq article (nnimap-find-article-by-message-id group article)))
535       (when (and result
536                  article)
537         (erase-buffer)
538         (with-current-buffer (nnimap-buffer)
539           (erase-buffer)
540           (when nnimap-fetch-partial-articles
541             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
542             (goto-char (point-min))
543             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
544               (setq structure (ignore-errors
545                                 (let ((start (point)))
546                                   (forward-sexp 1)
547                                   (downcase-region start (point))
548                                   (goto-char start)
549                                   (read (current-buffer))))
550                     parts (nnimap-find-wanted-parts structure))))
551           (when (if parts
552                     (nnimap-get-partial-article article parts structure)
553                   (nnimap-get-whole-article article))
554             (let ((buffer (current-buffer)))
555               (with-current-buffer (or to-buffer nntp-server-buffer)
556                 (nnheader-insert-buffer-substring buffer)
557                 (nnheader-ms-strip-cr)))
558             (cons group article)))))))
559
560 (deffoo nnimap-request-head (article &optional group server to-buffer)
561   (when group
562     (setq group (nnimap-decode-gnus-group group)))
563   (when (nnimap-possibly-change-group group server)
564     (with-current-buffer (nnimap-buffer)
565       (when (stringp article)
566         (setq article (nnimap-find-article-by-message-id group article)))
567       (if (null article)
568           nil
569         (nnimap-get-whole-article
570          article (format "UID FETCH %%d %s"
571                          (nnimap-header-parameters)))
572         (let ((buffer (current-buffer)))
573           (with-current-buffer (or to-buffer nntp-server-buffer)
574             (erase-buffer)
575             (insert-buffer-substring buffer)
576             (nnheader-ms-strip-cr)
577             (cons group article)))))))
578
579 (defun nnimap-get-whole-article (article &optional command)
580   (let ((result
581          (nnimap-command
582           (or command
583               (if (nnimap-ver4-p)
584                   "UID FETCH %d BODY.PEEK[]"
585                 "UID FETCH %d RFC822.PEEK"))
586           article)))
587     ;; Check that we really got an article.
588     (goto-char (point-min))
589     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
590       (setq result nil))
591     (when result
592       ;; Remove any data that may have arrived before the FETCH data.
593       (beginning-of-line)
594       (unless (bobp)
595         (delete-region (point-min) (point)))
596       (let ((bytes (nnimap-get-length)))
597         (delete-region (line-beginning-position)
598                        (progn (forward-line 1) (point)))
599         (goto-char (+ (point) bytes))
600         (delete-region (point) (point-max)))
601       t)))
602
603 (defun nnimap-capability (capability)
604   (member capability (nnimap-capabilities nnimap-object)))
605
606 (defun nnimap-ver4-p ()
607   (nnimap-capability "IMAP4REV1"))
608
609 (defun nnimap-get-partial-article (article parts structure)
610   (let ((result
611          (nnimap-command
612           "UID FETCH %d (%s %s)"
613           article
614           (if (nnimap-ver4-p)
615               "BODY.PEEK[HEADER]"
616             "RFC822.HEADER")
617           (if (nnimap-ver4-p)
618               (mapconcat (lambda (part)
619                            (format "BODY.PEEK[%s]" part))
620                          parts " ")
621             (mapconcat (lambda (part)
622                          (format "RFC822.PEEK[%s]" part))
623                        parts " ")))))
624     (when result
625       (nnimap-convert-partial-article structure))))
626
627 (defun nnimap-convert-partial-article (structure)
628   ;; First just skip past the headers.
629   (goto-char (point-min))
630   (let ((bytes (nnimap-get-length))
631         id parts)
632     ;; Delete "FETCH" line.
633     (delete-region (line-beginning-position)
634                    (progn (forward-line 1) (point)))
635     (goto-char (+ (point) bytes))
636     ;; Collect all the body parts.
637     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
638       (setq id (match-string 1)
639             bytes (or (nnimap-get-length) 0))
640       (beginning-of-line)
641       (delete-region (point) (progn (forward-line 1) (point)))
642       (push (list id (buffer-substring (point) (+ (point) bytes)))
643             parts)
644       (delete-region (point) (+ (point) bytes)))
645     ;; Delete trailing junk.
646     (delete-region (point) (point-max))
647     ;; Now insert all the parts again where they fit in the structure.
648     (nnimap-insert-partial-structure structure parts)
649     t))
650
651 (defun nnimap-insert-partial-structure (structure parts &optional subp)
652   (let (type boundary)
653     (let ((bstruc structure))
654       (while (consp (car bstruc))
655         (pop bstruc))
656       (setq type (car bstruc))
657       (setq bstruc (car (cdr bstruc)))
658       (let ((has-boundary (member "boundary" bstruc)))
659         (when has-boundary
660           (setq boundary (cadr has-boundary)))))
661     (when subp
662       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
663                       (downcase type) boundary)))
664     (while (not (stringp (car structure)))
665       (insert "\n--" boundary "\n")
666       (if (consp (caar structure))
667           (nnimap-insert-partial-structure (pop structure) parts t)
668         (let ((bit (pop structure)))
669           (insert (format  "Content-type: %s/%s"
670                            (downcase (nth 0 bit))
671                            (downcase (nth 1 bit))))
672           (if (member "CHARSET" (nth 2 bit))
673               (insert (format
674                        "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
675             (insert "\n"))
676           (insert (format "Content-transfer-encoding: %s\n"
677                           (nth 5 bit)))
678           (insert "\n")
679           (when (assoc (nth 9 bit) parts)
680             (insert (cadr (assoc (nth 9 bit) parts)))))))
681     (insert "\n--" boundary "--\n")))
682
683 (defun nnimap-find-wanted-parts (structure)
684   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
685
686 (defun nnimap-find-wanted-parts-1 (structure prefix)
687   (let ((num 1)
688         parts)
689     (while (consp (car structure))
690       (let ((sub (pop structure)))
691         (if (consp (car sub))
692             (push (nnimap-find-wanted-parts-1
693                    sub (if (string= prefix "")
694                            (number-to-string num)
695                          (format "%s.%s" prefix num)))
696                   parts)
697           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
698                 (id (if (string= prefix "")
699                         (number-to-string num)
700                       (format "%s.%s" prefix num))))
701             (setcar (nthcdr 9 sub) id)
702             (when (if (eq nnimap-fetch-partial-articles t)
703                       (equal id "1")
704                     (string-match nnimap-fetch-partial-articles type))
705               (push id parts))))
706         (incf num)))
707     (nreverse parts)))
708
709 (defun nnimap-decode-gnus-group (group)
710   (decode-coding-string group 'utf-8))
711
712 (deffoo nnimap-request-group (group &optional server dont-check info)
713   (setq group (nnimap-decode-gnus-group group))
714   (let ((result (nnimap-possibly-change-group
715                  ;; Don't SELECT the group if we're going to select it
716                  ;; later, anyway.
717                  (if (and (not dont-check)
718                           (assoc group nnimap-current-infos))
719                      nil
720                    group)
721                  server))
722         articles active marks high low)
723     (with-current-buffer nntp-server-buffer
724       (when result
725         (if (and dont-check
726                  (setq active (nth 2 (assoc group nnimap-current-infos))))
727             (insert (format "211 %d %d %d %S\n"
728                             (- (cdr active) (car active))
729                             (car active)
730                             (cdr active)
731                             group))
732           (with-current-buffer (nnimap-buffer)
733             (erase-buffer)
734             (let ((group-sequence
735                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
736                   (flag-sequence
737                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
738               (setf (nnimap-group nnimap-object) group)
739               (nnimap-wait-for-response flag-sequence)
740               (setq marks
741                     (nnimap-flags-to-marks
742                      (nnimap-parse-flags
743                       (list (list group-sequence flag-sequence
744                                   1 group "SELECT")))))
745               (when (and info
746                          marks)
747                 (nnimap-update-infos marks (list info))
748                 (nnimap-store-info info (gnus-active (gnus-info-group info))))
749               (goto-char (point-max))
750               (let ((uidnext (nth 5 (car marks))))
751                 (setq high (or (if uidnext
752                                    (1- uidnext)
753                                  (nth 3 (car marks)))
754                                0)
755                       low (or (nth 4 (car marks)) uidnext 1)))))
756           (erase-buffer)
757           (insert
758            (format
759             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
760         t))))
761
762 (deffoo nnimap-request-create-group (group &optional server args)
763   (setq group (nnimap-decode-gnus-group group))
764   (when (nnimap-possibly-change-group nil server)
765     (with-current-buffer (nnimap-buffer)
766       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
767
768 (deffoo nnimap-request-delete-group (group &optional force server)
769   (setq group (nnimap-decode-gnus-group group))
770   (when (nnimap-possibly-change-group nil server)
771     (with-current-buffer (nnimap-buffer)
772       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
773
774 (deffoo nnimap-request-rename-group (group new-name &optional server)
775   (setq group (nnimap-decode-gnus-group group))
776   (when (nnimap-possibly-change-group nil server)
777     (with-current-buffer (nnimap-buffer)
778       (nnimap-unselect-group)
779       (car (nnimap-command "RENAME %S %S"
780                            (utf7-encode group t) (utf7-encode new-name t))))))
781
782 (defun nnimap-unselect-group ()
783   ;; Make sure we don't have this group open read/write by asking
784   ;; to examine a mailbox that doesn't exist.  This seems to be
785   ;; the only way that allows us to reliably go back to unselected
786   ;; state on Courier.
787   (nnimap-command "EXAMINE DOES.NOT.EXIST"))
788
789 (deffoo nnimap-request-expunge-group (group &optional server)
790   (setq group (nnimap-decode-gnus-group group))
791   (when (nnimap-possibly-change-group group server)
792     (with-current-buffer (nnimap-buffer)
793       (car (nnimap-command "EXPUNGE")))))
794
795 (defun nnimap-get-flags (spec)
796   (let ((articles nil)
797         elems end)
798     (with-current-buffer (nnimap-buffer)
799       (erase-buffer)
800       (nnimap-wait-for-response (nnimap-send-command
801                                  "UID FETCH %s FLAGS" spec))
802       (setq end (point))
803       (subst-char-in-region (point-min) (point-max)
804                             ?\\ ?% t)
805       (goto-char (point-min))
806       (while (search-forward " FETCH " end t)
807         (setq elems (read (current-buffer)))
808         (push (cons (cadr (memq 'UID elems))
809                     (cadr (memq 'FLAGS elems)))
810               articles)))
811     (nreverse articles)))
812
813 (deffoo nnimap-close-group (group &optional server)
814   t)
815
816 (deffoo nnimap-request-move-article (article group server accept-form
817                                              &optional last internal-move-group)
818   (setq group (nnimap-decode-gnus-group group))
819   (with-temp-buffer
820     (mm-disable-multibyte)
821     (when (funcall (if internal-move-group
822                        'nnimap-request-head
823                      'nnimap-request-article)
824                    article group server (current-buffer))
825       ;; If the move is internal (on the same server), just do it the easy
826       ;; way.
827       (let ((message-id (message-field-value "message-id")))
828         (if internal-move-group
829             (let ((result
830                    (with-current-buffer (nnimap-buffer)
831                      (nnimap-command "UID COPY %d %S"
832                                      article
833                                      (utf7-encode internal-move-group t)))))
834               (when (car result)
835                 (nnimap-delete-article article)
836                 (cons internal-move-group
837                       (or (nnimap-find-uid-response "COPYUID" (cadr result))
838                           (nnimap-find-article-by-message-id
839                            internal-move-group message-id)))))
840           ;; Move the article to a different method.
841           (let ((result (eval accept-form)))
842             (when result
843               (nnimap-delete-article article)
844               result)))))))
845
846 (deffoo nnimap-request-expire-articles (articles group &optional server force)
847   (setq group (nnimap-decode-gnus-group group))
848   (cond
849    ((null articles)
850     nil)
851    ((not (nnimap-possibly-change-group group server))
852     articles)
853    ((and force
854          (eq nnmail-expiry-target 'delete))
855     (unless (nnimap-delete-article (gnus-compress-sequence articles))
856       (nnheader-message 7 "Article marked for deletion, but not expunged."))
857     nil)
858    (t
859     (let ((deletable-articles
860            (if (or force
861                    (eq nnmail-expiry-wait 'immediate))
862                articles
863              (gnus-sorted-intersection
864               articles
865               (nnimap-find-expired-articles group)))))
866       (if (null deletable-articles)
867           articles
868         (if (eq nnmail-expiry-target 'delete)
869             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
870           (setq deletable-articles
871                 (nnimap-process-expiry-targets
872                  deletable-articles group server)))
873         ;; Return the articles we didn't delete.
874         (gnus-sorted-complement articles deletable-articles))))))
875
876 (defun nnimap-process-expiry-targets (articles group server)
877   (let ((deleted-articles nil))
878     (cond
879      ;; shortcut further processing if we're going to delete the articles
880      ((eq nnmail-expiry-target 'delete)
881       (setq deleted-articles articles)
882       t)
883      ;; or just move them to another folder on the same IMAP server
884      ((and (not (functionp nnmail-expiry-target))
885            (gnus-server-equal (gnus-group-method nnmail-expiry-target)
886                               (gnus-server-to-method
887                                (format "nnimap:%s" server))))
888       (and (nnimap-possibly-change-group group server)
889            (with-current-buffer (nnimap-buffer)
890              (nnheader-message 7 "Expiring articles from %s: %s" group articles)
891              (nnimap-command
892               "UID COPY %s %S"
893               (nnimap-article-ranges (gnus-compress-sequence articles))
894               (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
895              (setq deleted-articles articles)))
896       t)
897      (t
898       (dolist (article articles)
899         (let ((target nnmail-expiry-target))
900           (with-temp-buffer
901             (mm-disable-multibyte)
902             (when (nnimap-request-article article group server (current-buffer))
903               (when (functionp target)
904                 (setq target (funcall target group)))
905               (if (and target
906                        (not (eq target 'delete)))
907                   (if (or (gnus-request-group target t)
908                           (gnus-request-create-group target))
909                       (progn
910                         (nnmail-expiry-target-group target group)
911                         (nnheader-message 7 "Expiring article %s:%d to %s"
912                                           group article target))
913                     (setq target nil))
914                 (nnheader-message 7 "Expiring article %s:%d" group article))
915               (when target
916                 (push article deleted-articles))))))))
917     ;; Change back to the current group again.
918     (nnimap-possibly-change-group group server)
919     (setq deleted-articles (nreverse deleted-articles))
920     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
921     deleted-articles))
922
923 (defun nnimap-find-expired-articles (group)
924   (let ((cutoff (nnmail-expired-article-p group nil nil)))
925     (with-current-buffer (nnimap-buffer)
926       (let ((result
927              (nnimap-command
928               "UID SEARCH SENTBEFORE %s"
929               (format-time-string
930                (format "%%d-%s-%%Y"
931                        (upcase
932                         (car (rassoc (nth 4 (decode-time cutoff))
933                                      parse-time-months))))
934                cutoff))))
935         (and (car result)
936              (delete 0 (mapcar #'string-to-number
937                                (cdr (assoc "SEARCH" (cdr result))))))))))
938
939
940 (defun nnimap-find-article-by-message-id (group message-id)
941   (with-current-buffer (nnimap-buffer)
942     (erase-buffer)
943     (unless (equal group (nnimap-group nnimap-object))
944       (setf (nnimap-group nnimap-object) nil)
945       (setf (nnimap-examined nnimap-object) group)
946       (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
947     (let ((sequence
948            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
949           article result)
950       (setq result (nnimap-wait-for-response sequence))
951       (when (and result
952                  (car (setq result (nnimap-parse-response))))
953         ;; Select the last instance of the message in the group.
954         (and (setq article
955                    (car (last (cdr (assoc "SEARCH" (cdr result))))))
956              (string-to-number article))))))
957
958 (defun nnimap-delete-article (articles)
959   (with-current-buffer (nnimap-buffer)
960     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
961                     (nnimap-article-ranges articles))
962     (cond
963      ((nnimap-capability "UIDPLUS")
964       (nnimap-command "UID EXPUNGE %s"
965                       (nnimap-article-ranges articles))
966       t)
967      (nnimap-expunge
968       (nnimap-command "EXPUNGE")
969       t)
970      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
971                                 "server doesn't support UIDPLUS, so we won't "
972                                 "delete this article now"))))))
973
974 (deffoo nnimap-request-scan (&optional group server)
975   (when group
976     (setq group (nnimap-decode-gnus-group group)))
977   (when (and (nnimap-possibly-change-group nil server)
978              nnimap-inbox
979              nnimap-split-methods)
980     (nnheader-message 7 "nnimap %s splitting mail..." server)
981     (nnimap-split-incoming-mail)
982     (nnheader-message 7 "nnimap %s splitting mail...done" server)))
983
984 (defun nnimap-marks-to-flags (marks)
985   (let (flags flag)
986     (dolist (mark marks)
987       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
988         (push flag flags)))
989     flags))
990
991 (deffoo nnimap-request-update-group-status (group status &optional server)
992   (setq group (nnimap-decode-gnus-group group))
993   (when (nnimap-possibly-change-group nil server)
994     (let ((command (assoc
995                     status
996                     '((subscribe "SUBSCRIBE")
997                       (unsubscribe "UNSUBSCRIBE")))))
998       (when command
999         (with-current-buffer (nnimap-buffer)
1000           (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1001
1002 (deffoo nnimap-request-set-mark (group actions &optional server)
1003   (setq group (nnimap-decode-gnus-group group))
1004   (when (nnimap-possibly-change-group group server)
1005     (let (sequence)
1006       (with-current-buffer (nnimap-buffer)
1007         (erase-buffer)
1008         ;; Just send all the STORE commands without waiting for
1009         ;; response.  If they're successful, they're successful.
1010         (dolist (action actions)
1011           (destructuring-bind (range action marks) action
1012             (let ((flags (nnimap-marks-to-flags marks)))
1013               (when flags
1014                 (setq sequence (nnimap-send-command
1015                                 "UID STORE %s %sFLAGS.SILENT (%s)"
1016                                 (nnimap-article-ranges range)
1017                                 (cond
1018                                  ((eq action 'del) "-")
1019                                  ((eq action 'add) "+")
1020                                  ((eq action 'set) ""))
1021                                 (mapconcat #'identity flags " ")))))))
1022         ;; Wait for the last command to complete to avoid later
1023         ;; syncronisation problems with the stream.
1024         (when sequence
1025           (nnimap-wait-for-response sequence))))))
1026
1027 (deffoo nnimap-request-accept-article (group &optional server last)
1028   (setq group (nnimap-decode-gnus-group group))
1029   (when (nnimap-possibly-change-group nil server)
1030     (nnmail-check-syntax)
1031     (let ((message-id (message-field-value "message-id"))
1032           sequence message)
1033       (nnimap-add-cr)
1034       (setq message (buffer-substring-no-properties (point-min) (point-max)))
1035       (with-current-buffer (nnimap-buffer)
1036         (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1037                                 message))
1038           ;; If we have this group open read-only, then unselect it
1039           ;; before appending to it.
1040           (when (equal (nnimap-examined nnimap-object) group)
1041             (nnimap-unselect-group))
1042           (erase-buffer)
1043           (setq sequence (nnimap-send-command
1044                           "APPEND %S {%d}" (utf7-encode group t)
1045                           (length message)))
1046           (unless nnimap-streaming
1047             (nnimap-wait-for-connection "^[+]"))
1048           (process-send-string (get-buffer-process (current-buffer)) message)
1049           (process-send-string (get-buffer-process (current-buffer))
1050                                (if (nnimap-newlinep nnimap-object)
1051                                    "\n"
1052                                  "\r\n"))
1053           (let ((result (nnimap-get-response sequence)))
1054             (if (not (nnimap-ok-p result))
1055                 (progn
1056                   (nnheader-report 'nnimap "%s" result)
1057                   nil)
1058               (cons group
1059                     (or (nnimap-find-uid-response "APPENDUID" (car result))
1060                         (nnimap-find-article-by-message-id
1061                          group message-id))))))))))
1062
1063 (defun nnimap-process-quirk (greeting-match type data)
1064   (when (and (nnimap-greeting nnimap-object)
1065              (string-match greeting-match (nnimap-greeting nnimap-object))
1066              (eq type 'append)
1067              (string-match "\000" data))
1068     (let ((choice (gnus-multiple-choice
1069                    "Message contains NUL characters.  Delete, continue, abort? "
1070                    '((?d "Delete NUL characters")
1071                      (?c "Try to APPEND the message as is")
1072                      (?a "Abort")))))
1073       (cond
1074        ((eq choice ?a)
1075         (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1076        ((eq choice ?c)
1077         data)
1078        (t
1079         (with-temp-buffer
1080           (insert data)
1081           (goto-char (point-min))
1082           (while (search-forward "\000" nil t)
1083             (replace-match "" t t))
1084           (buffer-string)))))))
1085
1086 (defun nnimap-ok-p (value)
1087   (and (consp value)
1088        (consp (car value))
1089        (equal (caar value) "OK")))
1090
1091 (defun nnimap-find-uid-response (name list)
1092   (let ((result (car (last (nnimap-find-response-element name list)))))
1093     (and result
1094          (string-to-number result))))
1095
1096 (defun nnimap-find-response-element (name list)
1097   (let (result)
1098     (dolist (elem list)
1099       (when (and (consp elem)
1100                  (equal name (car elem)))
1101         (setq result elem)))
1102     result))
1103
1104 (deffoo nnimap-request-replace-article (article group buffer)
1105   (setq group (nnimap-decode-gnus-group group))
1106   (let (group-art)
1107     (when (and (nnimap-possibly-change-group group nil)
1108                ;; Put the article into the group.
1109                (with-current-buffer buffer
1110                  (setq group-art
1111                        (nnimap-request-accept-article group nil t))))
1112       (nnimap-delete-article (list article))
1113       ;; Return the new article number.
1114       (cdr group-art))))
1115
1116 (defun nnimap-add-cr ()
1117   (goto-char (point-min))
1118   (while (re-search-forward "\r?\n" nil t)
1119     (replace-match "\r\n" t t)))
1120
1121 (defun nnimap-get-groups ()
1122   (erase-buffer)
1123   (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1124         groups)
1125     (nnimap-wait-for-response sequence)
1126     (subst-char-in-region (point-min) (point-max)
1127                           ?\\ ?% t)
1128     (goto-char (point-min))
1129     (nnimap-unfold-quoted-lines)
1130     (goto-char (point-min))
1131     (while (search-forward "* LIST " nil t)
1132       (let ((flags (read (current-buffer)))
1133             (separator (read (current-buffer)))
1134             (group (read (current-buffer))))
1135         (unless (member '%NoSelect flags)
1136           (push (utf7-decode (if (stringp group)
1137                                  group
1138                                (format "%s" group)) t)
1139                 groups))))
1140     (nreverse groups)))
1141
1142 (deffoo nnimap-request-list (&optional server)
1143   (when (nnimap-possibly-change-group nil server)
1144     (with-current-buffer nntp-server-buffer
1145       (erase-buffer)
1146       (let ((groups
1147              (with-current-buffer (nnimap-buffer)
1148                (nnimap-get-groups)))
1149             sequences responses)
1150         (when groups
1151           (with-current-buffer (nnimap-buffer)
1152             (setf (nnimap-group nnimap-object) nil)
1153             (dolist (group groups)
1154               (setf (nnimap-examined nnimap-object) group)
1155               (push (list (nnimap-send-command "EXAMINE %S"
1156                                                (utf7-encode group t))
1157                           group)
1158                     sequences))
1159             (nnimap-wait-for-response (caar sequences))
1160             (setq responses
1161                   (nnimap-get-responses (mapcar #'car sequences))))
1162           (dolist (response responses)
1163             (let* ((sequence (car response))
1164                    (response (cadr response))
1165                    (group (cadr (assoc sequence sequences))))
1166               (when (and group
1167                          (equal (caar response) "OK"))
1168                 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1169                       highest exists)
1170                   (dolist (elem response)
1171                     (when (equal (cadr elem) "EXISTS")
1172                       (setq exists (string-to-number (car elem)))))
1173                   (when uidnext
1174                     (setq highest (1- (string-to-number (car uidnext)))))
1175                   (cond
1176                    ((null highest)
1177                     (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1178                    ((zerop exists)
1179                     ;; Empty group.
1180                     (insert (format "%S %d %d y\n"
1181                                     (utf7-decode group t)
1182                                     highest (1+ highest))))
1183                    (t
1184                     ;; Return the widest possible range.
1185                     (insert (format "%S %d 1 y\n" (utf7-decode group t)
1186                                     (or highest exists)))))))))
1187           t)))))
1188
1189 (deffoo nnimap-request-newgroups (date &optional server)
1190   (when (nnimap-possibly-change-group nil server)
1191     (with-current-buffer nntp-server-buffer
1192       (erase-buffer)
1193       (dolist (group (with-current-buffer (nnimap-buffer)
1194                        (nnimap-get-groups)))
1195         (unless (assoc group nnimap-current-infos)
1196           ;; Insert dummy numbers here -- they don't matter.
1197           (insert (format "%S 0 1 y\n" (utf7-encode group)))))
1198       t)))
1199
1200 (deffoo nnimap-retrieve-group-data-early (server infos)
1201   (when (nnimap-possibly-change-group nil server)
1202     (with-current-buffer (nnimap-buffer)
1203       (erase-buffer)
1204       (setf (nnimap-group nnimap-object) nil)
1205       (let ((qresyncp (nnimap-capability "QRESYNC"))
1206             params groups sequences active uidvalidity modseq group)
1207         ;; Go through the infos and gather the data needed to know
1208         ;; what and how to request the data.
1209         (dolist (info infos)
1210           (setq params (gnus-info-params info)
1211                 group (nnimap-decode-gnus-group
1212                        (gnus-group-real-name (gnus-info-group info)))
1213                 active (cdr (assq 'active params))
1214                 uidvalidity (cdr (assq 'uidvalidity params))
1215                 modseq (cdr (assq 'modseq params)))
1216           (setf (nnimap-examined nnimap-object) group)
1217           (if (and qresyncp
1218                    uidvalidity
1219                    active
1220                    modseq)
1221               (push
1222                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1223                                           (utf7-encode group t)
1224                                           (nnimap-quirk "QRESYNC")
1225                                           uidvalidity modseq)
1226                      'qresync
1227                      nil group 'qresync)
1228                sequences)
1229             (let ((start
1230                    (if (and active uidvalidity)
1231                        ;; Fetch the last 100 flags.
1232                        (max 1 (- (cdr active) 100))
1233                      1))
1234                   (command
1235                    (if uidvalidity
1236                        "EXAMINE"
1237                      ;; If we don't have a UIDVALIDITY, then this is
1238                      ;; the first time we've seen the group, so we
1239                      ;; have to do a SELECT (which is slower than an
1240                      ;; examine), but will tell us whether the group
1241                      ;; is read-only or not.
1242                      "SELECT")))
1243               (push (list (nnimap-send-command "%s %S" command
1244                                                (utf7-encode group t))
1245                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1246                           start group command)
1247                     sequences))))
1248         sequences))))
1249
1250 (defun nnimap-quirk (command)
1251   (let ((quirk (assoc command nnimap-quirks)))
1252     ;; If this server is of a type that matches a quirk, then return
1253     ;; the "quirked" command instead of the proper one.
1254     (if (or (null quirk)
1255             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1256         command
1257       (nth 2 quirk))))
1258
1259 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1260   (when (and sequences
1261              ;; Check that the process is still alive.
1262              (get-buffer-process (nnimap-buffer))
1263              (memq (process-status (get-buffer-process (nnimap-buffer)))
1264                    '(open run))
1265              (nnimap-possibly-change-group nil server))
1266     (with-current-buffer (nnimap-buffer)
1267       ;; Wait for the final data to trickle in.
1268       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1269                                           (caar sequences)
1270                                         (cadar sequences))
1271                                       t)
1272         ;; Now we should have most of the data we need, no matter
1273         ;; whether we're QRESYNCING, fetching all the flags from
1274         ;; scratch, or just fetching the last 100 flags per group.
1275         (nnimap-update-infos (nnimap-flags-to-marks
1276                               (nnimap-parse-flags
1277                                (nreverse sequences)))
1278                              infos)
1279         ;; Finally, just return something resembling an active file in
1280         ;; the nntp buffer, so that the agent can save the info, too.
1281         (with-current-buffer nntp-server-buffer
1282           (erase-buffer)
1283           (dolist (info infos)
1284             (let* ((group (gnus-info-group info))
1285                    (active (gnus-active group)))
1286               (when active
1287                 (insert (format "%S %d %d y\n"
1288                                 (decode-coding-string
1289                                  (gnus-group-real-name group) 'utf-8)
1290                                 (cdr active)
1291                                 (car active)))))))))))
1292
1293 (defun nnimap-update-infos (flags infos)
1294   (dolist (info infos)
1295     (let* ((group (nnimap-decode-gnus-group
1296                    (gnus-group-real-name (gnus-info-group info))))
1297            (marks (cdr (assoc group flags))))
1298       (when marks
1299         (nnimap-update-info info marks)))))
1300
1301 (defun nnimap-update-info (info marks)
1302   (destructuring-bind (existing flags high low uidnext start-article
1303                                 permanent-flags uidvalidity
1304                                 vanished highestmodseq) marks
1305     (cond
1306      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1307      ;; completely empty groups.
1308      ((and (not existing)
1309            (not uidnext))
1310       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1311         (when active
1312           (gnus-set-active (gnus-info-group info) active))))
1313      ;; We have a mismatch between the old and new UIDVALIDITY
1314      ;; identifiers, so we have to re-request the group info (the next
1315      ;; time).  This virtually never happens.
1316      ((let ((old-uidvalidity
1317              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1318         (and old-uidvalidity
1319              (not (equal old-uidvalidity uidvalidity))
1320              (> start-article 1)))
1321       (gnus-group-remove-parameter info 'uidvalidity)
1322       (gnus-group-remove-parameter info 'modseq))
1323      ;; We have the data needed to update.
1324      (t
1325       (let* ((group (gnus-info-group info))
1326              (completep (and start-article
1327                              (= start-article 1)))
1328              (active (or (gnus-active group)
1329                          (cdr (assq 'active (gnus-info-params info))))))
1330         (when uidnext
1331           (setq high (1- uidnext)))
1332         ;; First set the active ranges based on high/low.
1333         (if (or completep
1334                 (not (gnus-active group)))
1335             (gnus-set-active group
1336                              (cond
1337                               (active
1338                                (cons (min (or low (car active))
1339                                           (car active))
1340                                      (max (or high (cdr active))
1341                                           (cdr active))))
1342                               ((and low high)
1343                                (cons low high))
1344                               (uidnext
1345                                ;; No articles in this group.
1346                                (cons uidnext (1- uidnext)))
1347                               (start-article
1348                                (cons start-article (1- start-article)))
1349                               (t
1350                                ;; No articles and no uidnext.
1351                                nil)))
1352           (gnus-set-active group
1353                            (cons (car active)
1354                                  (or high (1- uidnext)))))
1355         ;; See whether this is a read-only group.
1356         (unless (eq permanent-flags 'not-scanned)
1357           (gnus-group-set-parameter
1358            info 'permanent-flags
1359            (and (or (memq '%* permanent-flags)
1360                     (memq '%Seen permanent-flags))
1361                 permanent-flags)))
1362         ;; Update marks and read articles if this isn't a
1363         ;; read-only IMAP group.
1364         (when (setq permanent-flags
1365                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1366           (if (and highestmodseq
1367                    (not start-article))
1368               ;; We've gotten the data by QRESYNCing.
1369               (nnimap-update-qresync-info
1370                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1371             ;; Do normal non-QRESYNC flag updates.
1372             ;; Update the list of read articles.
1373             (let* ((unread
1374                     (gnus-compress-sequence
1375                      (gnus-set-difference
1376                       (gnus-set-difference
1377                        existing
1378                        (cdr (assoc '%Seen flags)))
1379                       (cdr (assoc '%Flagged flags)))))
1380                    (read (gnus-range-difference
1381                           (cons start-article high) unread)))
1382               (when (> start-article 1)
1383                 (setq read
1384                       (gnus-range-nconcat
1385                        (if (> start-article 1)
1386                            (gnus-sorted-range-intersection
1387                             (cons 1 (1- start-article))
1388                             (gnus-info-read info))
1389                          (gnus-info-read info))
1390                        read)))
1391               (when (or (not (listp permanent-flags))
1392                         (memq '%Seen permanent-flags))
1393                 (gnus-info-set-read info read))
1394               ;; Update the marks.
1395               (setq marks (gnus-info-marks info))
1396               (dolist (type (cdr nnimap-mark-alist))
1397                 (when (or (not (listp permanent-flags))
1398                           (memq (car (assoc (caddr type) flags))
1399                                 permanent-flags)
1400                           (memq '%* permanent-flags))
1401                   (let ((old-marks (assoc (car type) marks))
1402                         (new-marks
1403                          (gnus-compress-sequence
1404                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1405                                    (assoc (intern (cadr type) obarray) flags)
1406                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1407                     (setq marks (delq old-marks marks))
1408                     (pop old-marks)
1409                     (when (and old-marks
1410                                (> start-article 1))
1411                       (setq old-marks (gnus-range-difference
1412                                        old-marks
1413                                        (cons start-article high)))
1414                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1415                     (when new-marks
1416                       (push (cons (car type) new-marks) marks)))))
1417               (gnus-info-set-marks info marks t))))
1418         ;; Tell Gnus whether there are any \Recent messages in any of
1419         ;; the groups.
1420         (let ((recent (cdr (assoc '%Recent flags))))
1421           (when (and active
1422                      recent
1423                      (> (car (last recent)) (cdr active)))
1424             (push (list (cons (gnus-group-real-name group) 0))
1425                   nnmail-split-history)))
1426         ;; Note the active level for the next run-through.
1427         (gnus-group-set-parameter info 'active (gnus-active group))
1428         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1429         (gnus-group-set-parameter info 'modseq highestmodseq)
1430         (nnimap-store-info info (gnus-active group)))))))
1431
1432 (defun nnimap-update-qresync-info (info existing vanished flags)
1433   ;; Add all the vanished articles to the list of read articles.
1434   (gnus-info-set-read
1435    info
1436    (gnus-add-to-range
1437     (gnus-add-to-range
1438      (gnus-range-add (gnus-info-read info)
1439                      vanished)
1440      (cdr (assq '%Flagged flags)))
1441     (cdr (assq '%Seen flags))))
1442   (let ((marks (gnus-info-marks info)))
1443     (dolist (type (cdr nnimap-mark-alist))
1444       (let ((ticks (assoc (car type) marks))
1445             (new-marks
1446              (cdr (or (assoc (caddr type) flags) ; %Flagged
1447                       (assoc (intern (cadr type) obarray) flags)
1448                       (assoc (cadr type) flags))))) ; "\Flagged"
1449         (setq marks (delq ticks marks))
1450         (pop ticks)
1451         ;; Add the new marks we got.
1452         (setq ticks (gnus-add-to-range ticks new-marks))
1453         ;; Remove the marks from messages that don't have them.
1454         (setq ticks (gnus-remove-from-range
1455                      ticks
1456                      (gnus-compress-sequence
1457                       (gnus-sorted-complement existing new-marks))))
1458         (when ticks
1459           (push (cons (car type) ticks) marks)))
1460       (gnus-info-set-marks info marks t))))
1461
1462 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1463   (if (zerop (length irange))
1464       nil
1465     (let ((result nil))
1466       (dolist (elem (split-string irange ","))
1467         (push
1468          (if (string-match ":" elem)
1469              (let ((numbers (split-string elem ":")))
1470                (cons (string-to-number (car numbers))
1471                      (string-to-number (cadr numbers))))
1472            (string-to-number elem))
1473          result))
1474       (nreverse result))))
1475
1476 (defun nnimap-store-info (info active)
1477   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1478          (entry (assoc group nnimap-current-infos)))
1479     (if entry
1480         (setcdr entry (list info active))
1481       (push (list group info active) nnimap-current-infos))))
1482
1483 (defun nnimap-flags-to-marks (groups)
1484   (let (data group totalp uidnext articles start-article mark permanent-flags
1485              uidvalidity vanished highestmodseq)
1486     (dolist (elem groups)
1487       (setq group (car elem)
1488             uidnext (nth 1 elem)
1489             start-article (nth 2 elem)
1490             permanent-flags (nth 3 elem)
1491             uidvalidity (nth 4 elem)
1492             vanished (nth 5 elem)
1493             highestmodseq (nth 6 elem)
1494             articles (nthcdr 7 elem))
1495       (let ((high (caar articles))
1496             marks low existing)
1497         (dolist (article articles)
1498           (setq low (car article))
1499           (push (car article) existing)
1500           (dolist (flag (cdr article))
1501             (setq mark (assoc flag marks))
1502             (if (not mark)
1503                 (push (list flag (car article)) marks)
1504               (setcdr mark (cons (car article) (cdr mark))))))
1505         (push (list group existing marks high low uidnext start-article
1506                     permanent-flags uidvalidity vanished highestmodseq)
1507               data)))
1508     data))
1509
1510 (defun nnimap-parse-flags (sequences)
1511   (goto-char (point-min))
1512   ;; Change \Delete etc to %Delete, so that the reader can read it.
1513   (subst-char-in-region (point-min) (point-max)
1514                         ?\\ ?% t)
1515   ;; Remove any MODSEQ entries in the buffer, because they may contain
1516   ;; numbers that are too large for 32-bit Emacsen.
1517   (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1518     (replace-match "" t t))
1519   (goto-char (point-min))
1520   (let (start end articles groups uidnext elems permanent-flags
1521               uidvalidity vanished highestmodseq)
1522     (dolist (elem sequences)
1523       (destructuring-bind (group-sequence flag-sequence totalp group command)
1524           elem
1525         (setq start (point))
1526         (when (and
1527                ;; The EXAMINE was successful.
1528                (search-forward (format "\n%d OK " group-sequence) nil t)
1529                (progn
1530                  (forward-line 1)
1531                  (setq end (point))
1532                  (goto-char start)
1533                  (setq permanent-flags
1534                        (if (equal command "SELECT")
1535                            (and (search-forward "PERMANENTFLAGS "
1536                                                 (or end (point-min)) t)
1537                                 (read (current-buffer)))
1538                          'not-scanned))
1539                  (goto-char start)
1540                  (setq uidnext
1541                        (and (search-forward "UIDNEXT "
1542                                             (or end (point-min)) t)
1543                             (read (current-buffer))))
1544                  (goto-char start)
1545                  (setq uidvalidity
1546                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1547                                                (or end (point-min)) t)
1548                             ;; Store UIDVALIDITY as a string, as it's
1549                             ;; too big for 32-bit Emacsen, usually.
1550                             (match-string 1)))
1551                  (goto-char start)
1552                  (setq vanished
1553                        (and (eq flag-sequence 'qresync)
1554                             (re-search-forward "^\\* VANISHED .* \\([0-9:,]+\\)"
1555                                                (or end (point-min)) t)
1556                             (match-string 1)))
1557                  (goto-char start)
1558                  (setq highestmodseq
1559                        (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1560                                             (or end (point-min)) t)
1561                             (match-string 1)))
1562                  (goto-char end)
1563                  (forward-line -1))
1564                ;; The UID FETCH FLAGS was successful.
1565                (or (eq flag-sequence 'qresync)
1566                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1567           (if (eq flag-sequence 'qresync)
1568               (progn
1569                 (goto-char start)
1570                 (setq start end))
1571             (setq start (point))
1572             (goto-char end))
1573           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1574             (let ((p (point)))
1575               (setq elems (read (current-buffer)))
1576               (push (cons (cadr (memq 'UID elems))
1577                           (cadr (memq 'FLAGS elems)))
1578                     articles)))
1579           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1580                              vanished highestmodseq)
1581                        articles)
1582                 groups)
1583           (goto-char end)
1584           (setq articles nil))))
1585     groups))
1586
1587 (defun nnimap-find-process-buffer (buffer)
1588   (cadr (assoc buffer nnimap-connection-alist)))
1589
1590 (deffoo nnimap-request-post (&optional server)
1591   (setq nnimap-status-string "Read-only server")
1592   nil)
1593
1594 (declare-function gnus-fetch-headers "gnus-sum"
1595                   (articles &optional limit force-new dependencies))
1596
1597 (deffoo nnimap-request-thread (header &optional group server)
1598   (when group
1599     (setq group (nnimap-decode-gnus-group group)))
1600   (if gnus-refer-thread-use-nnir
1601       (nnir-search-thread header)
1602     (when (nnimap-possibly-change-group group server)
1603       (let* ((cmd (nnimap-make-thread-query header))
1604              (result (with-current-buffer (nnimap-buffer)
1605                        (nnimap-command  "UID SEARCH %s" cmd))))
1606         (when result
1607           (gnus-fetch-headers
1608            (and (car result) (delete 0 (mapcar #'string-to-number
1609                                                (cdr (assoc "SEARCH" (cdr result))))))
1610            nil t))))))
1611
1612 (defun nnimap-possibly-change-group (group server)
1613   (let ((open-result t))
1614     (when (and server
1615                (not (nnimap-server-opened server)))
1616       (setq open-result (nnimap-open-server server)))
1617     (cond
1618      ((not open-result)
1619       nil)
1620      ((not group)
1621       t)
1622      (t
1623       (with-current-buffer (nnimap-buffer)
1624         (if (equal group (nnimap-group nnimap-object))
1625             t
1626           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1627             (when (car result)
1628               (setf (nnimap-group nnimap-object) group
1629                     (nnimap-select-result nnimap-object) result)
1630               result))))))))
1631
1632 (defun nnimap-find-connection (buffer)
1633   "Find the connection delivering to BUFFER."
1634   (let ((entry (assoc buffer nnimap-connection-alist)))
1635     (when entry
1636       (if (and (buffer-name (cadr entry))
1637                (get-buffer-process (cadr entry))
1638                (memq (process-status (get-buffer-process (cadr entry)))
1639                      '(open run)))
1640           (get-buffer-process (cadr entry))
1641         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1642         nil))))
1643
1644 (defvar nnimap-sequence 0)
1645
1646 (defun nnimap-send-command (&rest args)
1647   (setf (nnimap-last-command-time nnimap-object) (current-time))
1648   (process-send-string
1649    (get-buffer-process (current-buffer))
1650    (nnimap-log-command
1651     (format "%d %s%s\n"
1652             (incf nnimap-sequence)
1653             (apply #'format args)
1654             (if (nnimap-newlinep nnimap-object)
1655                 ""
1656               "\r"))))
1657   ;; Some servers apparently can't have many outstanding
1658   ;; commands, so throttle them.
1659   (unless nnimap-streaming
1660     (nnimap-wait-for-response nnimap-sequence))
1661   nnimap-sequence)
1662
1663 (defun nnimap-log-command (command)
1664   (with-current-buffer (get-buffer-create "*imap log*")
1665     (goto-char (point-max))
1666     (insert (format-time-string "%H:%M:%S") " "
1667             (if nnimap-inhibit-logging
1668                 "(inhibited)\n"
1669               command)))
1670   command)
1671
1672 (defun nnimap-command (&rest args)
1673   (erase-buffer)
1674   (let* ((sequence (apply #'nnimap-send-command args))
1675          (response (nnimap-get-response sequence)))
1676     (if (equal (caar response) "OK")
1677         (cons t response)
1678       (nnheader-report 'nnimap "%s"
1679                        (mapconcat (lambda (a)
1680                                     (format "%s" a))
1681                                   (car response) " "))
1682       nil)))
1683
1684 (defun nnimap-get-response (sequence)
1685   (nnimap-wait-for-response sequence)
1686   (nnimap-parse-response))
1687
1688 (defun nnimap-wait-for-connection (&optional regexp)
1689   (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1690
1691 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1692   (let ((process (get-buffer-process (current-buffer))))
1693     (goto-char (point-min))
1694     (while (and (memq (process-status process)
1695                       '(open run))
1696                 (not (re-search-forward regexp nil t)))
1697       (nnheader-accept-process-output process)
1698       (goto-char (point-min)))
1699     (forward-line -1)
1700     (and (looking-at (or response-regexp regexp))
1701          (match-string 1))))
1702
1703 (defun nnimap-wait-for-response (sequence &optional messagep)
1704   (let ((process (get-buffer-process (current-buffer)))
1705         openp)
1706     (condition-case nil
1707         (progn
1708           (goto-char (point-max))
1709           (while (and (setq openp (memq (process-status process)
1710                                         '(open run)))
1711                       (progn
1712                         ;; Skip past any "*" lines that the server has
1713                         ;; output.
1714                         (while (and (not (bobp))
1715                                     (progn
1716                                       (forward-line -1)
1717                                       (looking-at "\\*"))))
1718                         (not (looking-at (format "%d .*\n" sequence)))))
1719             (when messagep
1720               (nnheader-message 7 "nnimap read %dk" (/ (buffer-size) 1000)))
1721             (nnheader-accept-process-output process)
1722             (goto-char (point-max)))
1723           openp)
1724       (quit
1725        (when debug-on-quit
1726          (debug "Quit"))
1727        ;; The user hit C-g while we were waiting: kill the process, in case
1728        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1729        ;; NAT routers).
1730        (delete-process process)
1731        nil))))
1732
1733 (defun nnimap-parse-response ()
1734   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1735         result)
1736     (dolist (line lines)
1737       (push (cdr (nnimap-parse-line line)) result))
1738     ;; Return the OK/error code first, and then all the "continuation
1739     ;; lines" afterwards.
1740     (cons (pop result)
1741           (nreverse result))))
1742
1743 ;; Parse an IMAP response line lightly.  They look like
1744 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1745 ;; the lines into a list of strings and lists of string.
1746 (defun nnimap-parse-line (line)
1747   (let (char result)
1748     (with-temp-buffer
1749       (mm-disable-multibyte)
1750       (insert line)
1751       (goto-char (point-min))
1752       (while (not (eobp))
1753         (if (eql (setq char (following-char)) ? )
1754             (forward-char 1)
1755           (push
1756            (cond
1757             ((eql char ?\[)
1758              (split-string
1759               (buffer-substring
1760                (1+ (point))
1761                (if (search-forward "]" (line-end-position) 'move)
1762                    (1- (point))
1763                  (point)))))
1764             ((eql char ?\()
1765              (split-string
1766               (buffer-substring
1767                (1+ (point))
1768                (if (search-forward ")" (line-end-position) 'move)
1769                    (1- (point))
1770                  (point)))))
1771             ((eql char ?\")
1772              (forward-char 1)
1773              (buffer-substring
1774               (point)
1775               (1- (or (search-forward "\"" (line-end-position) 'move)
1776                       (point)))))
1777             (t
1778              (buffer-substring (point) (if (search-forward " " nil t)
1779                                            (1- (point))
1780                                          (goto-char (point-max))))))
1781            result)))
1782       (nreverse result))))
1783
1784 (defun nnimap-last-response-string ()
1785   (save-excursion
1786     (forward-line 1)
1787     (let ((end (point)))
1788       (forward-line -1)
1789       (when (not (bobp))
1790         (forward-line -1)
1791         (while (and (not (bobp))
1792                     (eql (following-char) ?*))
1793           (forward-line -1))
1794         (unless (eql (following-char) ?*)
1795           (forward-line 1)))
1796       (buffer-substring (point) end))))
1797
1798 (defun nnimap-get-responses (sequences)
1799   (let (responses)
1800     (dolist (sequence sequences)
1801       (goto-char (point-min))
1802       (when (re-search-forward (format "^%d " sequence) nil t)
1803         (push (list sequence (nnimap-parse-response))
1804               responses)))
1805     responses))
1806
1807 (defvar nnimap-incoming-split-list nil)
1808
1809 (defun nnimap-fetch-inbox (articles)
1810   (erase-buffer)
1811   (nnimap-wait-for-response
1812    (nnimap-send-command
1813     "UID FETCH %s %s"
1814     (nnimap-article-ranges articles)
1815     (format "(UID %s%s)"
1816             (format
1817              (if (nnimap-ver4-p)
1818                  "BODY.PEEK"
1819                "RFC822.PEEK"))
1820             (cond
1821              (nnimap-split-download-body-default
1822               "[]")
1823              ((nnimap-ver4-p)
1824               "[HEADER]")
1825              (t
1826               "[1]"))))
1827    t))
1828
1829 (defun nnimap-split-incoming-mail ()
1830   (with-current-buffer (nnimap-buffer)
1831     (let ((nnimap-incoming-split-list nil)
1832           (nnmail-split-methods
1833            (cond
1834             ((eq nnimap-split-methods 'default)
1835              nnmail-split-methods)
1836             (nnimap-split-methods
1837              nnimap-split-methods)
1838             (nnimap-split-fancy
1839              'nnmail-split-fancy)))
1840           (nnmail-split-fancy (or nnimap-split-fancy
1841                                   nnmail-split-fancy))
1842           (nnmail-inhibit-default-split-group t)
1843           (groups (nnimap-get-groups))
1844           new-articles)
1845       (erase-buffer)
1846       (nnimap-command "SELECT %S" nnimap-inbox)
1847       (setf (nnimap-group nnimap-object) nnimap-inbox)
1848       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1849       (when new-articles
1850         (nnimap-fetch-inbox new-articles)
1851         (nnimap-transform-split-mail)
1852         (nnheader-ms-strip-cr)
1853         (nnmail-cache-open)
1854         (nnmail-split-incoming (current-buffer)
1855                                #'nnimap-save-mail-spec
1856                                nil nil
1857                                #'nnimap-dummy-active-number
1858                                #'nnimap-save-mail-spec)
1859         (when nnimap-incoming-split-list
1860           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1861                 sequences junk-articles)
1862             ;; Create any groups that doesn't already exist on the
1863             ;; server first.
1864             (dolist (spec specs)
1865               (when (and (not (member (car spec) groups))
1866                          (not (eq (car spec) 'junk)))
1867                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1868             ;; Then copy over all the messages.
1869             (erase-buffer)
1870             (dolist (spec specs)
1871               (let ((group (car spec))
1872                     (ranges (cdr spec)))
1873                 (if (eq group 'junk)
1874                     (setq junk-articles ranges)
1875                   (push (list (nnimap-send-command
1876                                "UID COPY %s %S"
1877                                (nnimap-article-ranges ranges)
1878                                (utf7-encode group t))
1879                               ranges)
1880                         sequences))))
1881             ;; Wait for the last COPY response...
1882             (when sequences
1883               (nnimap-wait-for-response (caar sequences))
1884               ;; And then mark the successful copy actions as deleted,
1885               ;; and possibly expunge them.
1886               (nnimap-mark-and-expunge-incoming
1887                (nnimap-parse-copied-articles sequences)))
1888             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1889
1890 (defun nnimap-mark-and-expunge-incoming (range)
1891   (when range
1892     (setq range (nnimap-article-ranges range))
1893     (erase-buffer)
1894     (let ((sequence
1895            (nnimap-send-command
1896             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1897       (cond
1898        ;; If the server supports it, we now delete the message we have
1899        ;; just copied over.
1900        ((nnimap-capability "UIDPLUS")
1901         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1902        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1903        ;; user has configured it.
1904        (nnimap-expunge
1905         (setq sequence (nnimap-send-command "EXPUNGE"))))
1906       (nnimap-wait-for-response sequence))))
1907
1908 (defun nnimap-parse-copied-articles (sequences)
1909   (let (sequence copied range)
1910     (goto-char (point-min))
1911     (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
1912       (setq sequence (string-to-number (match-string 1)))
1913       (when (setq range (cadr (assq sequence sequences)))
1914         (push (gnus-uncompress-range range) copied)))
1915     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1916
1917 (defun nnimap-new-articles (flags)
1918   (let (new)
1919     (dolist (elem flags)
1920       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1921                                       (cdr elem))
1922         (push (car elem) new)))
1923     (gnus-compress-sequence (nreverse new))))
1924
1925 (defun nnimap-make-split-specs (list)
1926   (let ((specs nil)
1927         entry)
1928     (dolist (elem list)
1929       (destructuring-bind (article spec) elem
1930         (dolist (group (delete nil (mapcar #'car spec)))
1931           (unless (setq entry (assoc group specs))
1932             (push (setq entry (list group)) specs))
1933           (setcdr entry (cons article (cdr entry))))))
1934     (dolist (entry specs)
1935       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1936     specs))
1937
1938 (defun nnimap-transform-split-mail ()
1939   (goto-char (point-min))
1940   (let (article bytes)
1941     (block nil
1942       (while (not (eobp))
1943         (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
1944           (delete-region (point) (progn (forward-line 1) (point)))
1945           (when (eobp)
1946             (return)))
1947         (setq article (match-string 1)
1948               bytes (nnimap-get-length))
1949         (delete-region (line-beginning-position) (line-end-position))
1950         ;; Insert MMDF separator, and a way to remember what this
1951         ;; article UID is.
1952         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1953         (forward-char (1+ bytes))
1954         (setq bytes (nnimap-get-length))
1955         (delete-region (line-beginning-position) (line-end-position))
1956         ;; There's a body; skip past that.
1957         (when bytes
1958           (forward-char (1+ bytes))
1959           (delete-region (line-beginning-position) (line-end-position)))))))
1960
1961 (defun nnimap-dummy-active-number (group &optional server)
1962   1)
1963
1964 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1965   (let (article)
1966     (goto-char (point-min))
1967     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1968         (error "Invalid nnimap mail")
1969       (setq article (string-to-number (match-string 1))))
1970     (push (list article
1971                 (if (eq group-art 'junk)
1972                     (list (cons 'junk 1))
1973                   group-art))
1974           nnimap-incoming-split-list)))
1975
1976 (defun nnimap-make-thread-query (header)
1977   (let* ((id  (mail-header-id header))
1978          (refs (split-string
1979                 (or (mail-header-references header)
1980                     "")))
1981          (value
1982           (format
1983            "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
1984            id id)))
1985     (dolist (refid refs value)
1986       (setq value (format
1987                    "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
1988                    refid refid value)))))
1989
1990
1991 (provide 'nnimap)
1992
1993 ;;; nnimap.el ends here