Don't log login commands.
[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 &optional inhibit-create)
280   (let* ((found (nth 0 (auth-source-search :max 1
281                                            :host address
282                                            :port ports
283                                            :create (if inhibit-create
284                                                        nil
285                                                      (null ports)))))
286          (user (plist-get found :user))
287          (secret (plist-get found :secret))
288          (secret (if (functionp secret) (funcall secret) secret)))
289     (if found
290         (list user 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                                 (list
390                                  (nnoo-current-server 'nnimap)
391                                  nnimap-address)
392                                 ports t))))
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 :protocol 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   (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" (utf7-encode group t))
1091                         group)
1092                   sequences))
1093           (nnimap-wait-for-response (caar sequences))
1094           (setq responses
1095                 (nnimap-get-responses (mapcar #'car sequences))))
1096         (dolist (response responses)
1097           (let* ((sequence (car response))
1098                  (response (cadr response))
1099                  (group (cadr (assoc sequence sequences))))
1100             (when (and group
1101                        (equal (caar response) "OK"))
1102               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1103                     highest exists)
1104                 (dolist (elem response)
1105                   (when (equal (cadr elem) "EXISTS")
1106                     (setq exists (string-to-number (car elem)))))
1107                 (when uidnext
1108                   (setq highest (1- (string-to-number (car uidnext)))))
1109                 (cond
1110                  ((null highest)
1111                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1112                  ((zerop exists)
1113                   ;; Empty group.
1114                   (insert (format "%S %d %d y\n"
1115                                   (utf7-decode group t) highest (1+ highest))))
1116                  (t
1117                   ;; Return the widest possible range.
1118                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
1119                                   (or highest exists)))))))))
1120         t))))
1121
1122 (deffoo nnimap-request-newgroups (date &optional server)
1123   (nnimap-possibly-change-group nil server)
1124   (with-current-buffer nntp-server-buffer
1125     (erase-buffer)
1126     (dolist (group (with-current-buffer (nnimap-buffer)
1127                      (nnimap-get-groups)))
1128       (unless (assoc group nnimap-current-infos)
1129         ;; Insert dummy numbers here -- they don't matter.
1130         (insert (format "%S 0 1 y\n" group))))
1131     t))
1132
1133 (deffoo nnimap-retrieve-group-data-early (server infos)
1134   (when (nnimap-possibly-change-group nil server)
1135     (with-current-buffer (nnimap-buffer)
1136       (erase-buffer)
1137       (setf (nnimap-group nnimap-object) nil)
1138       (let ((qresyncp (nnimap-capability "QRESYNC"))
1139             params groups sequences active uidvalidity modseq group)
1140         ;; Go through the infos and gather the data needed to know
1141         ;; what and how to request the data.
1142         (dolist (info infos)
1143           (setq params (gnus-info-params info)
1144                 group (gnus-group-real-name (gnus-info-group info))
1145                 active (cdr (assq 'active params))
1146                 uidvalidity (cdr (assq 'uidvalidity params))
1147                 modseq (cdr (assq 'modseq params)))
1148           (setf (nnimap-examined nnimap-object) group)
1149           (if (and qresyncp
1150                    uidvalidity
1151                    modseq)
1152               (push
1153                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1154                                           (utf7-encode group t)
1155                                           (nnimap-quirk "QRESYNC")
1156                                           uidvalidity modseq)
1157                      'qresync
1158                      nil group 'qresync)
1159                sequences)
1160             (let ((start
1161                    (if (and active uidvalidity)
1162                        ;; Fetch the last 100 flags.
1163                        (max 1 (- (cdr active) 100))
1164                      1))
1165                   (command
1166                    (if uidvalidity
1167                        "EXAMINE"
1168                      ;; If we don't have a UIDVALIDITY, then this is
1169                      ;; the first time we've seen the group, so we
1170                      ;; have to do a SELECT (which is slower than an
1171                      ;; examine), but will tell us whether the group
1172                      ;; is read-only or not.
1173                      "SELECT")))
1174               (push (list (nnimap-send-command "%s %S" command
1175                                                (utf7-encode group t))
1176                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1177                           start group command)
1178                     sequences))))
1179         sequences))))
1180
1181 (defun nnimap-quirk (command)
1182   (let ((quirk (assoc command nnimap-quirks)))
1183     ;; If this server is of a type that matches a quirk, then return
1184     ;; the "quirked" command instead of the proper one.
1185     (if (or (null quirk)
1186             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1187         command
1188       (nth 2 quirk))))
1189
1190 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1191   (when (and sequences
1192              (nnimap-possibly-change-group nil server))
1193     (with-current-buffer (nnimap-buffer)
1194       ;; Wait for the final data to trickle in.
1195       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1196                                           (caar sequences)
1197                                         (cadar sequences))
1198                                       t)
1199         ;; Now we should have most of the data we need, no matter
1200         ;; whether we're QRESYNCING, fetching all the flags from
1201         ;; scratch, or just fetching the last 100 flags per group.
1202         (nnimap-update-infos (nnimap-flags-to-marks
1203                               (nnimap-parse-flags
1204                                (nreverse sequences)))
1205                              infos)
1206         ;; Finally, just return something resembling an active file in
1207         ;; the nntp buffer, so that the agent can save the info, too.
1208         (with-current-buffer nntp-server-buffer
1209           (erase-buffer)
1210           (dolist (info infos)
1211             (let* ((group (gnus-info-group info))
1212                    (active (gnus-active group)))
1213               (when active
1214                 (insert (format "%S %d %d y\n"
1215                                 (gnus-group-real-name group)
1216                                 (cdr active)
1217                                 (car active)))))))))))
1218
1219 (defun nnimap-update-infos (flags infos)
1220   (dolist (info infos)
1221     (let* ((group (gnus-group-real-name (gnus-info-group info)))
1222            (marks (cdr (assoc group flags))))
1223       (when marks
1224         (nnimap-update-info info marks)))))
1225
1226 (defun nnimap-update-info (info marks)
1227   (destructuring-bind (existing flags high low uidnext start-article
1228                                 permanent-flags uidvalidity
1229                                 vanished highestmodseq) marks
1230     (cond
1231      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1232      ;; completely empty groups.
1233      ((and (not existing)
1234            (not uidnext))
1235       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1236         (when active
1237           (gnus-set-active (gnus-info-group info) active))))
1238      ;; We have a mismatch between the old and new UIDVALIDITY
1239      ;; identifiers, so we have to re-request the group info (the next
1240      ;; time).  This virtually never happens.
1241      ((let ((old-uidvalidity
1242              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1243         (and old-uidvalidity
1244              (not (equal old-uidvalidity uidvalidity))
1245              (> start-article 1)))
1246       (gnus-group-remove-parameter info 'uidvalidity)
1247       (gnus-group-remove-parameter info 'modseq))
1248      ;; We have the data needed to update.
1249      (t
1250       (let* ((group (gnus-info-group info))
1251              (completep (and start-article
1252                              (= start-article 1)))
1253              (active (or (gnus-active group)
1254                          (cdr (assq 'active (gnus-info-params info))))))
1255         (when uidnext
1256           (setq high (1- uidnext)))
1257         ;; First set the active ranges based on high/low.
1258         (if (or completep
1259                 (not (gnus-active group)))
1260             (gnus-set-active group
1261                              (cond
1262                               (active
1263                                (cons (min (or low (car active))
1264                                           (car active))
1265                                      (max (or high (cdr active))
1266                                           (cdr active))))
1267                               ((and low high)
1268                                (cons low high))
1269                               (uidnext
1270                                ;; No articles in this group.
1271                                (cons uidnext (1- uidnext)))
1272                               (start-article
1273                                (cons start-article (1- start-article)))
1274                               (t
1275                                ;; No articles and no uidnext.
1276                                nil)))
1277           (gnus-set-active group
1278                            (cons (car active)
1279                                  (or high (1- uidnext)))))
1280         ;; See whether this is a read-only group.
1281         (unless (eq permanent-flags 'not-scanned)
1282           (gnus-group-set-parameter
1283            info 'permanent-flags
1284            (and (or (memq '%* permanent-flags)
1285                     (memq '%Seen permanent-flags))
1286                 permanent-flags)))
1287         ;; Update marks and read articles if this isn't a
1288         ;; read-only IMAP group.
1289         (when (setq permanent-flags
1290                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1291           (if (and highestmodseq
1292                    (not start-article))
1293               ;; We've gotten the data by QRESYNCing.
1294               (nnimap-update-qresync-info
1295                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1296             ;; Do normal non-QRESYNC flag updates.
1297             ;; Update the list of read articles.
1298             (let* ((unread
1299                     (gnus-compress-sequence
1300                      (gnus-set-difference
1301                       (gnus-set-difference
1302                        existing
1303                        (cdr (assoc '%Seen flags)))
1304                       (cdr (assoc '%Flagged flags)))))
1305                    (read (gnus-range-difference
1306                           (cons start-article high) unread)))
1307               (when (> start-article 1)
1308                 (setq read
1309                       (gnus-range-nconcat
1310                        (if (> start-article 1)
1311                            (gnus-sorted-range-intersection
1312                             (cons 1 (1- start-article))
1313                             (gnus-info-read info))
1314                          (gnus-info-read info))
1315                        read)))
1316               (when (or (not (listp permanent-flags))
1317                         (memq '%Seen permanent-flags))
1318                 (gnus-info-set-read info read))
1319               ;; Update the marks.
1320               (setq marks (gnus-info-marks info))
1321               (dolist (type (cdr nnimap-mark-alist))
1322                 (when (or (not (listp permanent-flags))
1323                           (memq (car (assoc (caddr type) flags))
1324                                 permanent-flags)
1325                           (memq '%* permanent-flags))
1326                   (let ((old-marks (assoc (car type) marks))
1327                         (new-marks
1328                          (gnus-compress-sequence
1329                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1330                                    (assoc (intern (cadr type) obarray) flags)
1331                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1332                     (setq marks (delq old-marks marks))
1333                     (pop old-marks)
1334                     (when (and old-marks
1335                                (> start-article 1))
1336                       (setq old-marks (gnus-range-difference
1337                                        old-marks
1338                                        (cons start-article high)))
1339                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1340                     (when new-marks
1341                       (push (cons (car type) new-marks) marks)))))
1342               (gnus-info-set-marks info marks t))))
1343         ;; Tell Gnus whether there are any \Recent messages in any of
1344         ;; the groups.
1345         (let ((recent (cdr (assoc '%Recent flags))))
1346           (when (and active
1347                      recent
1348                      (> (car (last recent)) (cdr active)))
1349             (push (list (cons (gnus-group-real-name group) 0))
1350                   nnmail-split-history)))
1351         ;; Note the active level for the next run-through.
1352         (gnus-group-set-parameter info 'active (gnus-active group))
1353         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1354         (gnus-group-set-parameter info 'modseq highestmodseq)
1355         (nnimap-store-info info (gnus-active group)))))))
1356
1357 (defun nnimap-update-qresync-info (info existing vanished flags)
1358   ;; Add all the vanished articles to the list of read articles.
1359   (gnus-info-set-read
1360    info
1361    (gnus-add-to-range
1362     (gnus-add-to-range
1363      (gnus-range-add (gnus-info-read info)
1364                      vanished)
1365      (cdr (assq '%Flagged flags)))
1366     (cdr (assq '%Seen flags))))
1367   (let ((marks (gnus-info-marks info)))
1368     (dolist (type (cdr nnimap-mark-alist))
1369       (let ((ticks (assoc (car type) marks))
1370             (new-marks
1371              (cdr (or (assoc (caddr type) flags) ; %Flagged
1372                       (assoc (intern (cadr type) obarray) flags)
1373                       (assoc (cadr type) flags))))) ; "\Flagged"
1374         (setq marks (delq ticks marks))
1375         (pop ticks)
1376         ;; Add the new marks we got.
1377         (setq ticks (gnus-add-to-range ticks new-marks))
1378         ;; Remove the marks from messages that don't have them.
1379         (setq ticks (gnus-remove-from-range
1380                      ticks
1381                      (gnus-compress-sequence
1382                       (gnus-sorted-complement existing new-marks))))
1383         (when ticks
1384           (push (cons (car type) ticks) marks)))
1385       (gnus-info-set-marks info marks t))))
1386
1387 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1388   (if (zerop (length irange))
1389       nil
1390     (let ((result nil))
1391       (dolist (elem (split-string irange ","))
1392         (push
1393          (if (string-match ":" elem)
1394              (let ((numbers (split-string elem ":")))
1395                (cons (string-to-number (car numbers))
1396                      (string-to-number (cadr numbers))))
1397            (string-to-number elem))
1398          result))
1399       (nreverse result))))
1400
1401 (defun nnimap-store-info (info active)
1402   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1403          (entry (assoc group nnimap-current-infos)))
1404     (if entry
1405         (setcdr entry (list info active))
1406       (push (list group info active) nnimap-current-infos))))
1407
1408 (defun nnimap-flags-to-marks (groups)
1409   (let (data group totalp uidnext articles start-article mark permanent-flags
1410              uidvalidity vanished highestmodseq)
1411     (dolist (elem groups)
1412       (setq group (car elem)
1413             uidnext (nth 1 elem)
1414             start-article (nth 2 elem)
1415             permanent-flags (nth 3 elem)
1416             uidvalidity (nth 4 elem)
1417             vanished (nth 5 elem)
1418             highestmodseq (nth 6 elem)
1419             articles (nthcdr 7 elem))
1420       (let ((high (caar articles))
1421             marks low existing)
1422         (dolist (article articles)
1423           (setq low (car article))
1424           (push (car article) existing)
1425           (dolist (flag (cdr article))
1426             (setq mark (assoc flag marks))
1427             (if (not mark)
1428                 (push (list flag (car article)) marks)
1429               (setcdr mark (cons (car article) (cdr mark))))))
1430         (push (list group existing marks high low uidnext start-article
1431                     permanent-flags uidvalidity vanished highestmodseq)
1432               data)))
1433     data))
1434
1435 (defun nnimap-parse-flags (sequences)
1436   (goto-char (point-min))
1437   ;; Change \Delete etc to %Delete, so that the reader can read it.
1438   (subst-char-in-region (point-min) (point-max)
1439                         ?\\ ?% t)
1440   (let (start end articles groups uidnext elems permanent-flags
1441               uidvalidity vanished highestmodseq)
1442     (dolist (elem sequences)
1443       (destructuring-bind (group-sequence flag-sequence totalp group command)
1444           elem
1445         (setq start (point))
1446         (when (and
1447                ;; The EXAMINE was successful.
1448                (search-forward (format "\n%d OK " group-sequence) nil t)
1449                (progn
1450                  (forward-line 1)
1451                  (setq end (point))
1452                  (goto-char start)
1453                  (setq permanent-flags
1454                        (if (equal command "SELECT")
1455                            (and (search-forward "PERMANENTFLAGS "
1456                                                 (or end (point-min)) t)
1457                                 (read (current-buffer)))
1458                          'not-scanned))
1459                  (goto-char start)
1460                  (setq uidnext
1461                        (and (search-forward "UIDNEXT "
1462                                             (or end (point-min)) t)
1463                             (read (current-buffer))))
1464                  (goto-char start)
1465                  (setq uidvalidity
1466                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1467                                                (or end (point-min)) t)
1468                             ;; Store UIDVALIDITY as a string, as it's
1469                             ;; too big for 32-bit Emacsen, usually.
1470                             (match-string 1)))
1471                  (goto-char start)
1472                  (setq vanished
1473                        (and (eq flag-sequence 'qresync)
1474                             (re-search-forward "^\\* VANISHED .* \\([0-9:,]+\\)"
1475                                                (or end (point-min)) t)
1476                             (match-string 1)))
1477                  (goto-char start)
1478                  (setq highestmodseq
1479                        (and (search-forward "HIGHESTMODSEQ "
1480                                             (or end (point-min)) t)
1481                             (read (current-buffer))))
1482                  (goto-char end)
1483                  (forward-line -1))
1484                ;; The UID FETCH FLAGS was successful.
1485                (or (eq flag-sequence 'qresync)
1486                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1487           (if (eq flag-sequence 'qresync)
1488               (progn
1489                 (goto-char start)
1490                 (setq start end))
1491             (setq start (point))
1492             (goto-char end))
1493           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1494             (setq elems (read (current-buffer)))
1495             (push (cons (cadr (memq 'UID elems))
1496                         (cadr (memq 'FLAGS elems)))
1497                   articles))
1498           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1499                              vanished highestmodseq)
1500                        articles)
1501                 groups)
1502           (goto-char end)
1503           (setq articles nil))))
1504     groups))
1505
1506 (defun nnimap-find-process-buffer (buffer)
1507   (cadr (assoc buffer nnimap-connection-alist)))
1508
1509 (deffoo nnimap-request-post (&optional server)
1510   (setq nnimap-status-string "Read-only server")
1511   nil)
1512
1513 (declare-function gnus-fetch-headers "gnus-sum"
1514                   (articles &optional limit force-new dependencies))
1515
1516 (deffoo nnimap-request-thread (header)
1517   (let* ((id (mail-header-id header))
1518          (refs (split-string
1519                 (or (mail-header-references header)
1520                     "")))
1521          (cmd (let ((value
1522                      (format
1523                       "(OR HEADER REFERENCES %s HEADER Message-Id %s)"
1524                       id id)))
1525                 (dolist (refid refs value)
1526                   (setq value (format
1527                                "(OR (OR HEADER Message-Id %s HEADER REFERENCES %s) %s)"
1528                                refid refid value)))))
1529          (result (with-current-buffer (nnimap-buffer)
1530                    (nnimap-command  "UID SEARCH %s" cmd))))
1531     (gnus-fetch-headers
1532      (and (car result) (delete 0 (mapcar #'string-to-number
1533                                          (cdr (assoc "SEARCH" (cdr result))))))
1534      nil t)))
1535
1536 (defun nnimap-possibly-change-group (group server)
1537   (let ((open-result t))
1538     (when (and server
1539                (not (nnimap-server-opened server)))
1540       (setq open-result (nnimap-open-server server)))
1541     (cond
1542      ((not open-result)
1543       nil)
1544      ((not group)
1545       t)
1546      (t
1547       (with-current-buffer (nnimap-buffer)
1548         (if (equal group (nnimap-group nnimap-object))
1549             t
1550           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1551             (when (car result)
1552               (setf (nnimap-group nnimap-object) group
1553                     (nnimap-select-result nnimap-object) result)
1554               result))))))))
1555
1556 (defun nnimap-find-connection (buffer)
1557   "Find the connection delivering to BUFFER."
1558   (let ((entry (assoc buffer nnimap-connection-alist)))
1559     (when entry
1560       (if (and (buffer-name (cadr entry))
1561                (get-buffer-process (cadr entry))
1562                (memq (process-status (get-buffer-process (cadr entry)))
1563                      '(open run)))
1564           (get-buffer-process (cadr entry))
1565         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1566         nil))))
1567
1568 (defvar nnimap-sequence 0)
1569
1570 (defun nnimap-send-command (&rest args)
1571   (setf (nnimap-last-command-time nnimap-object) (current-time))
1572   (process-send-string
1573    (get-buffer-process (current-buffer))
1574    (nnimap-log-command
1575     (format "%d %s%s\n"
1576             (incf nnimap-sequence)
1577             (apply #'format args)
1578             (if (nnimap-newlinep nnimap-object)
1579                 ""
1580               "\r"))))
1581   ;; Some servers apparently can't have many outstanding
1582   ;; commands, so throttle them.
1583   (unless nnimap-streaming
1584     (nnimap-wait-for-response nnimap-sequence))
1585   nnimap-sequence)
1586
1587 (defun nnimap-log-command (command)
1588   (with-current-buffer (get-buffer-create "*imap log*")
1589     (goto-char (point-max))
1590     (insert (format-time-string "%H:%M:%S") " "
1591             (if nnimap-inhibit-logging
1592                 "(inhibited)"
1593               command)))
1594   command)
1595
1596 (defun nnimap-command (&rest args)
1597   (erase-buffer)
1598   (let* ((sequence (apply #'nnimap-send-command args))
1599          (response (nnimap-get-response sequence)))
1600     (if (equal (caar response) "OK")
1601         (cons t response)
1602       (nnheader-report 'nnimap "%s"
1603                        (mapconcat (lambda (a)
1604                                     (format "%s" a))
1605                                   (car response) " "))
1606       nil)))
1607
1608 (defun nnimap-get-response (sequence)
1609   (nnimap-wait-for-response sequence)
1610   (nnimap-parse-response))
1611
1612 (defun nnimap-wait-for-connection (&optional regexp)
1613   (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1614
1615 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1616   (let ((process (get-buffer-process (current-buffer))))
1617     (goto-char (point-min))
1618     (while (and (memq (process-status process)
1619                       '(open run))
1620                 (not (re-search-forward regexp nil t)))
1621       (nnheader-accept-process-output process)
1622       (goto-char (point-min)))
1623     (forward-line -1)
1624     (and (looking-at (or response-regexp regexp))
1625          (match-string 1))))
1626
1627 (defun nnimap-wait-for-response (sequence &optional messagep)
1628   (let ((process (get-buffer-process (current-buffer)))
1629         openp)
1630     (condition-case nil
1631         (progn
1632           (goto-char (point-max))
1633           (while (and (setq openp (memq (process-status process)
1634                                         '(open run)))
1635                       (progn
1636                         ;; Skip past any "*" lines that the server has
1637                         ;; output.
1638                         (while (and (not (bobp))
1639                                     (progn
1640                                       (forward-line -1)
1641                                       (looking-at "\\*"))))
1642                         (not (looking-at (format "%d " sequence)))))
1643             (when messagep
1644               (nnheader-message 7 "nnimap read %dk" (/ (buffer-size) 1000)))
1645             (nnheader-accept-process-output process)
1646             (goto-char (point-max)))
1647           openp)
1648       (quit
1649        ;; The user hit C-g while we were waiting: kill the process, in case
1650        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1651        ;; NAT routers).
1652        (delete-process process)
1653        nil))))
1654
1655 (defun nnimap-parse-response ()
1656   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1657         result)
1658     (dolist (line lines)
1659       (push (cdr (nnimap-parse-line line)) result))
1660     ;; Return the OK/error code first, and then all the "continuation
1661     ;; lines" afterwards.
1662     (cons (pop result)
1663           (nreverse result))))
1664
1665 ;; Parse an IMAP response line lightly.  They look like
1666 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1667 ;; the lines into a list of strings and lists of string.
1668 (defun nnimap-parse-line (line)
1669   (let (char result)
1670     (with-temp-buffer
1671       (mm-disable-multibyte)
1672       (insert line)
1673       (goto-char (point-min))
1674       (while (not (eobp))
1675         (if (eql (setq char (following-char)) ? )
1676             (forward-char 1)
1677           (push
1678            (cond
1679             ((eql char ?\[)
1680              (split-string
1681               (buffer-substring
1682                (1+ (point))
1683                (if (search-forward "]" (line-end-position) 'move)
1684                    (1- (point))
1685                  (point)))))
1686             ((eql char ?\()
1687              (split-string
1688               (buffer-substring
1689                (1+ (point))
1690                (if (search-forward ")" (line-end-position) 'move)
1691                    (1- (point))
1692                  (point)))))
1693             ((eql char ?\")
1694              (forward-char 1)
1695              (buffer-substring
1696               (point)
1697               (1- (or (search-forward "\"" (line-end-position) 'move)
1698                       (point)))))
1699             (t
1700              (buffer-substring (point) (if (search-forward " " nil t)
1701                                            (1- (point))
1702                                          (goto-char (point-max))))))
1703            result)))
1704       (nreverse result))))
1705
1706 (defun nnimap-last-response-string ()
1707   (save-excursion
1708     (forward-line 1)
1709     (let ((end (point)))
1710       (forward-line -1)
1711       (when (not (bobp))
1712         (forward-line -1)
1713         (while (and (not (bobp))
1714                     (eql (following-char) ?*))
1715           (forward-line -1))
1716         (unless (eql (following-char) ?*)
1717           (forward-line 1)))
1718       (buffer-substring (point) end))))
1719
1720 (defun nnimap-get-responses (sequences)
1721   (let (responses)
1722     (dolist (sequence sequences)
1723       (goto-char (point-min))
1724       (when (re-search-forward (format "^%d " sequence) nil t)
1725         (push (list sequence (nnimap-parse-response))
1726               responses)))
1727     responses))
1728
1729 (defvar nnimap-incoming-split-list nil)
1730
1731 (defun nnimap-fetch-inbox (articles)
1732   (erase-buffer)
1733   (nnimap-wait-for-response
1734    (nnimap-send-command
1735     "UID FETCH %s %s"
1736     (nnimap-article-ranges articles)
1737     (format "(UID %s%s)"
1738             (format
1739              (if (nnimap-ver4-p)
1740                  "BODY.PEEK[HEADER] BODY.PEEK"
1741                "RFC822.PEEK"))
1742             (if nnimap-split-download-body-default
1743                 "[]"
1744               "[1]")))
1745    t))
1746
1747 (defun nnimap-split-incoming-mail ()
1748   (with-current-buffer (nnimap-buffer)
1749     (let ((nnimap-incoming-split-list nil)
1750           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1751                                     nnmail-split-methods
1752                                   nnimap-split-methods))
1753           (nnmail-split-fancy (or nnimap-split-fancy
1754                                   nnmail-split-fancy))
1755           (nnmail-inhibit-default-split-group t)
1756           (groups (nnimap-get-groups))
1757           new-articles)
1758       (erase-buffer)
1759       (nnimap-command "SELECT %S" nnimap-inbox)
1760       (setf (nnimap-group nnimap-object) nnimap-inbox)
1761       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1762       (when new-articles
1763         (nnimap-fetch-inbox new-articles)
1764         (nnimap-transform-split-mail)
1765         (nnheader-ms-strip-cr)
1766         (nnmail-cache-open)
1767         (nnmail-split-incoming (current-buffer)
1768                                #'nnimap-save-mail-spec
1769                                nil nil
1770                                #'nnimap-dummy-active-number
1771                                #'nnimap-save-mail-spec)
1772         (when nnimap-incoming-split-list
1773           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1774                 sequences junk-articles)
1775             ;; Create any groups that doesn't already exist on the
1776             ;; server first.
1777             (dolist (spec specs)
1778               (when (and (not (member (car spec) groups))
1779                          (not (eq (car spec) 'junk)))
1780                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1781             ;; Then copy over all the messages.
1782             (erase-buffer)
1783             (dolist (spec specs)
1784               (let ((group (car spec))
1785                     (ranges (cdr spec)))
1786                 (if (eq group 'junk)
1787                     (setq junk-articles ranges)
1788                   (push (list (nnimap-send-command
1789                                "UID COPY %s %S"
1790                                (nnimap-article-ranges ranges)
1791                                (utf7-encode group t))
1792                               ranges)
1793                         sequences))))
1794             ;; Wait for the last COPY response...
1795             (when sequences
1796               (nnimap-wait-for-response (caar sequences))
1797               ;; And then mark the successful copy actions as deleted,
1798               ;; and possibly expunge them.
1799               (nnimap-mark-and-expunge-incoming
1800                (nnimap-parse-copied-articles sequences)))
1801             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1802
1803 (defun nnimap-mark-and-expunge-incoming (range)
1804   (when range
1805     (setq range (nnimap-article-ranges range))
1806     (erase-buffer)
1807     (let ((sequence
1808            (nnimap-send-command
1809             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1810       (cond
1811        ;; If the server supports it, we now delete the message we have
1812        ;; just copied over.
1813        ((nnimap-capability "UIDPLUS")
1814         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1815        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1816        ;; user has configured it.
1817        (nnimap-expunge
1818         (setq sequence (nnimap-send-command "EXPUNGE"))))
1819       (nnimap-wait-for-response sequence))))
1820
1821 (defun nnimap-parse-copied-articles (sequences)
1822   (let (sequence copied range)
1823     (goto-char (point-min))
1824     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1825       (setq sequence (string-to-number (match-string 1)))
1826       (when (setq range (cadr (assq sequence sequences)))
1827         (push (gnus-uncompress-range range) copied)))
1828     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1829
1830 (defun nnimap-new-articles (flags)
1831   (let (new)
1832     (dolist (elem flags)
1833       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1834                                       (cdr elem))
1835         (push (car elem) new)))
1836     (gnus-compress-sequence (nreverse new))))
1837
1838 (defun nnimap-make-split-specs (list)
1839   (let ((specs nil)
1840         entry)
1841     (dolist (elem list)
1842       (destructuring-bind (article spec) elem
1843         (dolist (group (delete nil (mapcar #'car spec)))
1844           (unless (setq entry (assoc group specs))
1845             (push (setq entry (list group)) specs))
1846           (setcdr entry (cons article (cdr entry))))))
1847     (dolist (entry specs)
1848       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1849     specs))
1850
1851 (defun nnimap-transform-split-mail ()
1852   (goto-char (point-min))
1853   (let (article bytes)
1854     (block nil
1855       (while (not (eobp))
1856         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1857           (delete-region (point) (progn (forward-line 1) (point)))
1858           (when (eobp)
1859             (return)))
1860         (setq article (match-string 1)
1861               bytes (nnimap-get-length))
1862         (delete-region (line-beginning-position) (line-end-position))
1863         ;; Insert MMDF separator, and a way to remember what this
1864         ;; article UID is.
1865         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1866         (forward-char (1+ bytes))
1867         (setq bytes (nnimap-get-length))
1868         (delete-region (line-beginning-position) (line-end-position))
1869         ;; There's a body; skip past that.
1870         (when bytes
1871           (forward-char (1+ bytes))
1872           (delete-region (line-beginning-position) (line-end-position)))))))
1873
1874 (defun nnimap-dummy-active-number (group &optional server)
1875   1)
1876
1877 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1878   (let (article)
1879     (goto-char (point-min))
1880     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1881         (error "Invalid nnimap mail")
1882       (setq article (string-to-number (match-string 1))))
1883     (push (list article
1884                 (if (eq group-art 'junk)
1885                     (list (cons 'junk 1))
1886                   group-art))
1887           nnimap-incoming-split-list)))
1888
1889 (provide 'nnimap)
1890
1891 ;;; nnimap.el ends here