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