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