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