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