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