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