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