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