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