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