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