c256c8c730648bedb5096aa13ea745a44f8f5e5a
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010 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 (eval-and-compile
30   (require 'nnheader))
31
32 (eval-when-compile
33   (require 'cl))
34
35 (require 'nnheader)
36 (require 'gnus-util)
37 (require 'gnus)
38 (require 'nnoo)
39 (require 'netrc)
40 (require 'utf7)
41 (require 'parse-time)
42
43 (autoload 'auth-source-forget-user-or-password "auth-source")
44 (autoload 'auth-source-user-or-password "auth-source")
45
46 (nnoo-declare nnimap)
47
48 (defvoo nnimap-address nil
49   "The address of the IMAP server.")
50
51 (defvoo nnimap-server-port nil
52   "The IMAP port used.
53 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
54 it will default to `imap'.")
55
56 (defvoo nnimap-stream 'ssl
57   "How nnimap will talk to the IMAP server.
58 Values are `ssl', `network', `starttls' or `shell'.")
59
60 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
61                                  (if (listp imap-shell-program)
62                                      (car imap-shell-program)
63                                    imap-shell-program)
64                                "ssh %s imapd"))
65
66 (defvoo nnimap-inbox nil
67   "The mail box where incoming mail arrives and should be split out of.")
68
69 (defvoo nnimap-split-methods nil
70   "How mail is split.
71 Uses the same syntax as nnmail-split-methods")
72
73 (defvoo nnimap-authenticator nil
74   "How nnimap authenticate itself to the server.
75 Possible choices are nil (use default methods) or `anonymous'.")
76
77 (defvoo nnimap-expunge t
78   "If non-nil, expunge articles after deleting them.
79 This is always done if the server supports UID EXPUNGE, but it's
80 not done by default on servers that doesn't support that command.")
81
82 (defvoo nnimap-streaming t
83   "If non-nil, try to use streaming commands with IMAP servers.
84 Switching this off will make nnimap slower, but it helps with
85 some servers.")
86
87 (defvoo nnimap-connection-alist nil)
88
89 (defvoo nnimap-current-infos nil)
90
91 (defvoo nnimap-fetch-partial-articles nil
92   "If non-nil, Gnus will fetch partial articles.
93 If t, nnimap will fetch only the first part.  If a string, it
94 will fetch all parts that have types that match that string.  A
95 likely value would be \"text/\" to automatically fetch all
96 textual parts.")
97
98 (defvar nnimap-process nil)
99
100 (defvar nnimap-status-string "")
101
102 (defvar nnimap-split-download-body-default nil
103   "Internal variable with default value for `nnimap-split-download-body'.")
104
105 (defvar nnimap-keepalive-timer nil)
106 (defvar nnimap-process-buffers nil)
107
108 (defstruct nnimap
109   group process commands capabilities select-result newlinep server
110   last-command-time greeting)
111
112 (defvar nnimap-object nil)
113
114 (defvar nnimap-mark-alist
115   '((read "\\Seen" %Seen)
116     (tick "\\Flagged" %Flagged)
117     (reply "\\Answered" %Answered)
118     (expire "gnus-expire")
119     (dormant "gnus-dormant")
120     (score "gnus-score")
121     (save "gnus-save")
122     (download "gnus-download")
123     (forward "gnus-forward")))
124
125 (defun nnimap-buffer ()
126   (nnimap-find-process-buffer nntp-server-buffer))
127
128 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
129   (with-current-buffer nntp-server-buffer
130     (erase-buffer)
131     (when (nnimap-possibly-change-group group server)
132       (with-current-buffer (nnimap-buffer)
133         (erase-buffer)
134         (nnimap-wait-for-response
135          (nnimap-send-command
136           "UID FETCH %s %s"
137           (nnimap-article-ranges (gnus-compress-sequence articles))
138           (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
139                   (format
140                    (if (nnimap-ver4-p)
141                        "BODY.PEEK[HEADER.FIELDS %s]"
142                      "RFC822.HEADER.LINES %s")
143                    (append '(Subject From Date Message-Id
144                                      References In-Reply-To Xref)
145                            nnmail-extra-headers))))
146          t)
147         (nnimap-transform-headers))
148       (insert-buffer-substring
149        (nnimap-find-process-buffer (current-buffer))))
150     'headers))
151
152 (defun nnimap-transform-headers ()
153   (goto-char (point-min))
154   (let (article bytes lines size string)
155     (block nil
156       (while (not (eobp))
157         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
158           (delete-region (point) (progn (forward-line 1) (point)))
159           (when (eobp)
160             (return)))
161         (setq article (match-string 1))
162         ;; Unfold quoted {number} strings.
163         (while (re-search-forward "[^]] {\\([0-9]+\\)}\r\n"
164                                   (1+ (line-end-position)) t)
165           (setq size (string-to-number (match-string 1)))
166           (delete-region (+ (match-beginning 0) 2) (point))
167           (setq string (delete-region (point) (+ (point) size)))
168           (insert (format "%S" string)))
169         (setq bytes (nnimap-get-length)
170               lines nil)
171         (beginning-of-line)
172         (setq size
173               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
174                                       (line-end-position)
175                                       t)
176                    (match-string 1)))
177         (beginning-of-line)
178         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
179           (let ((structure (ignore-errors
180                              (read (current-buffer)))))
181             (while (and (consp structure)
182                         (not (stringp (car structure))))
183               (setq structure (car structure)))
184             (setq lines (nth 7 structure))))
185         (delete-region (line-beginning-position) (line-end-position))
186         (insert (format "211 %s Article retrieved." article))
187         (forward-line 1)
188         (when size
189           (insert (format "Chars: %s\n" size)))
190         (when lines
191           (insert (format "Lines: %s\n" lines)))
192         (re-search-forward "^\r$")
193         (delete-region (line-beginning-position) (line-end-position))
194         (insert ".")
195         (forward-line 1)))))
196
197 (defun nnimap-get-length ()
198   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
199        (string-to-number (match-string 1))))
200
201 (defun nnimap-article-ranges (ranges)
202   (let (result)
203     (cond
204      ((numberp ranges)
205       (number-to-string ranges))
206      ((numberp (cdr ranges))
207       (format "%d:%d" (car ranges) (cdr ranges)))
208      (t
209       (dolist (elem ranges)
210         (push
211          (if (consp elem)
212              (format "%d:%d" (car elem) (cdr elem))
213            (number-to-string elem))
214          result))
215       (mapconcat #'identity (nreverse result) ",")))))
216
217 (deffoo nnimap-open-server (server &optional defs)
218   (if (nnimap-server-opened server)
219       t
220     (unless (assq 'nnimap-address defs)
221       (setq defs (append defs (list (list 'nnimap-address server)))))
222     (nnoo-change-server 'nnimap server defs)
223     (or (nnimap-find-connection nntp-server-buffer)
224         (nnimap-open-connection nntp-server-buffer))))
225
226 (defun nnimap-make-process-buffer (buffer)
227   (with-current-buffer
228       (generate-new-buffer (format "*nnimap %s %s %s*"
229                                    nnimap-address nnimap-server-port
230                                    (gnus-buffer-exists-p buffer)))
231     (mm-disable-multibyte)
232     (buffer-disable-undo)
233     (gnus-add-buffer)
234     (set (make-local-variable 'after-change-functions) nil)
235     (set (make-local-variable 'nnimap-object)
236          (make-nnimap :server (nnoo-current-server 'nnimap)))
237     (push (list buffer (current-buffer)) nnimap-connection-alist)
238     (push (current-buffer) nnimap-process-buffers)
239     (current-buffer)))
240
241 (defun nnimap-open-shell-stream (name buffer host port)
242   (let ((process-connection-type nil))
243     (start-process name buffer shell-file-name
244                    shell-command-switch
245                    (format-spec
246                     nnimap-shell-program
247                     (format-spec-make
248                      ?s host
249                      ?p port)))))
250
251 (defun nnimap-credentials (address ports &optional inhibit-create)
252   (let (port credentials)
253     ;; Request the credentials from all ports, but only query on the
254     ;; last port if all the previous ones have failed.
255     (while (and (null credentials)
256                 (setq port (pop ports)))
257       (setq credentials
258             (auth-source-user-or-password
259              '("login" "password") address port nil
260              (if inhibit-create
261                  nil
262                (null ports)))))
263     credentials))
264
265 (defun nnimap-keepalive ()
266   (let ((now (current-time)))
267     (dolist (buffer nnimap-process-buffers)
268       (when (buffer-name buffer)
269         (with-current-buffer buffer
270           (when (and nnimap-object
271                      (nnimap-last-command-time nnimap-object)
272                      (> (time-to-seconds
273                          (time-subtract
274                           now
275                           (nnimap-last-command-time nnimap-object)))
276                         ;; More than five minutes since the last command.
277                         (* 5 60)))
278             (nnimap-send-command "NOOP")))))))
279
280 (defun nnimap-open-connection (buffer)
281   (unless nnimap-keepalive-timer
282     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
283                                               'nnimap-keepalive)))
284   (block nil
285     (with-current-buffer (nnimap-make-process-buffer buffer)
286       (let* ((coding-system-for-read 'binary)
287              (coding-system-for-write 'binary)
288              (port nil)
289              (ports
290               (cond
291                ((eq nnimap-stream 'network)
292                 (open-network-stream
293                  "*nnimap*" (current-buffer) nnimap-address
294                  (setq port
295                        (or nnimap-server-port
296                            (if (netrc-find-service-number "imap")
297                                "imap"
298                              "143"))))
299                 '("143" "imap"))
300                ((eq nnimap-stream 'shell)
301                 (nnimap-open-shell-stream
302                  "*nnimap*" (current-buffer) nnimap-address
303                  (setq port (or nnimap-server-port "imap")))
304                 '("imap"))
305                ((eq nnimap-stream 'starttls)
306                 (starttls-open-stream
307                  "*nnimap*" (current-buffer) nnimap-address
308                  (setq port (or nnimap-server-port "imap")))
309                 '("imap"))
310                ((eq nnimap-stream 'ssl)
311                 (open-tls-stream
312                  "*nnimap*" (current-buffer) nnimap-address
313                  (setq port
314                        (or nnimap-server-port
315                            (if (netrc-find-service-number "imaps")
316                                "imaps"
317                              "993"))))
318                 '("143" "993" "imap" "imaps"))))
319              connection-result login-result credentials)
320         (setf (nnimap-process nnimap-object)
321               (get-buffer-process (current-buffer)))
322         (if (not (and (nnimap-process nnimap-object)
323                       (memq (process-status (nnimap-process nnimap-object))
324                             '(open run))))
325             (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
326                              nnimap-address port nnimap-stream)
327           (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
328           (if (not (setq connection-result (nnimap-wait-for-connection)))
329               (nnheader-report 'nnimap
330                                "%s" (buffer-substring
331                                      (point) (line-end-position)))
332             ;; Store the greeting (for debugging purposes).
333             (setf (nnimap-greeting nnimap-object)
334                   (buffer-substring (line-beginning-position)
335                                     (line-end-position)))
336             ;; Store the capabilities.
337             (setf (nnimap-capabilities nnimap-object)
338                   (mapcar
339                    #'upcase
340                    (nnimap-find-parameter
341                     "CAPABILITY" (cdr (nnimap-command "CAPABILITY")))))
342             (when (eq nnimap-stream 'starttls)
343               (nnimap-command "STARTTLS")
344               (starttls-negotiate (nnimap-process nnimap-object)))
345             ;; If this is a STARTTLS-capable server, then sever the
346             ;; connection and start a STARTTLS connection instead.
347             (when (and (eq nnimap-stream 'network)
348                        (member "STARTTLS" (nnimap-capabilities nnimap-object)))
349               (let ((nnimap-stream 'starttls))
350                 (delete-process (nnimap-process nnimap-object))
351                 (kill-buffer (current-buffer))
352                 (return
353                  (nnimap-open-connection buffer))))
354             (when nnimap-server-port
355               (push (format "%s" nnimap-server-port) ports))
356             (unless (equal connection-result "PREAUTH")
357               (if (not (setq credentials
358                              (if (eq nnimap-authenticator 'anonymous)
359                                  (list "anonymous"
360                                        (message-make-address))
361                                (or
362                                 ;; First look for the credentials based
363                                 ;; on the virtual server name.
364                                 (nnimap-credentials
365                                  (nnoo-current-server 'nnimap) ports t)
366                                 ;; Then look them up based on the
367                                 ;; physical address.
368                                 (nnimap-credentials nnimap-address ports)))))
369                   (setq nnimap-object nil)
370                 (setq login-result (nnimap-command "LOGIN %S %S"
371                                                    (car credentials)
372                                                    (cadr credentials)))
373                 (unless (car login-result)
374                   ;; If the login failed, then forget the credentials
375                   ;; that are now possibly cached.
376                   (dolist (host (list (nnoo-current-server 'nnimap)
377                                       nnimap-address))
378                     (dolist (port ports)
379                       (dolist (element '("login" "password"))
380                         (auth-source-forget-user-or-password
381                          element host port))))
382                   (delete-process (nnimap-process nnimap-object))
383                   (setq nnimap-object nil))))
384             (when nnimap-object
385               (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
386                 (nnimap-command "ENABLE QRESYNC"))
387               t)))))))
388
389 (defun nnimap-find-parameter (parameter elems)
390   (let (result)
391     (dolist (elem elems)
392       (cond
393        ((equal (car elem) parameter)
394         (setq result (cdr elem)))
395        ((and (equal (car elem) "OK")
396              (consp (cadr elem))
397              (equal (caadr elem) parameter))
398         (setq result (cdr (cadr elem))))))
399     result))
400
401 (deffoo nnimap-close-server (&optional server)
402   t)
403
404 (deffoo nnimap-request-close ()
405   t)
406
407 (deffoo nnimap-server-opened (&optional server)
408   (and (nnoo-current-server-p 'nnimap server)
409        nntp-server-buffer
410        (gnus-buffer-live-p nntp-server-buffer)
411        (nnimap-find-connection nntp-server-buffer)))
412
413 (deffoo nnimap-status-message (&optional server)
414   nnimap-status-string)
415
416 (deffoo nnimap-request-article (article &optional group server to-buffer)
417   (with-current-buffer nntp-server-buffer
418     (let ((result (nnimap-possibly-change-group group server))
419           parts structure)
420       (when (stringp article)
421         (setq article (nnimap-find-article-by-message-id group article)))
422       (when (and result
423                  article)
424         (erase-buffer)
425         (with-current-buffer (nnimap-buffer)
426           (erase-buffer)
427           (when nnimap-fetch-partial-articles
428             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
429             (goto-char (point-min))
430             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
431               (setq structure (ignore-errors (read (current-buffer)))
432                     parts (nnimap-find-wanted-parts structure))))
433           (when (if parts
434                     (nnimap-get-partial-article article parts structure)
435                   (nnimap-get-whole-article article))
436             (let ((buffer (current-buffer)))
437               (with-current-buffer (or to-buffer nntp-server-buffer)
438                 (erase-buffer)
439                 (insert-buffer-substring buffer)
440                 (nnheader-ms-strip-cr)
441                 (cons group article)))))))))
442
443 (defun nnimap-get-whole-article (article)
444   (let ((result
445          (nnimap-command
446           (if (nnimap-ver4-p)
447               "UID FETCH %d BODY.PEEK[]"
448             "UID FETCH %d RFC822.PEEK")
449           article)))
450     ;; Check that we really got an article.
451     (goto-char (point-min))
452     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
453       (setq result nil))
454     (when result
455       ;; Remove any data that may have arrived before the FETCH data.
456       (beginning-of-line)
457       (unless (bobp)
458         (delete-region (point-min) (point)))
459       (let ((bytes (nnimap-get-length)))
460         (delete-region (line-beginning-position)
461                        (progn (forward-line 1) (point)))
462         (goto-char (+ (point) bytes))
463         (delete-region (point) (point-max)))
464       t)))
465
466 (defun nnimap-ver4-p ()
467   (member "IMAP4REV1" (nnimap-capabilities nnimap-object)))
468
469 (defun nnimap-get-partial-article (article parts structure)
470   (let ((result
471          (nnimap-command
472           "UID FETCH %d (%s %s)"
473           article
474           (if (nnimap-ver4-p)
475               "BODY.PEEK[HEADER]"
476             "RFC822.HEADER")
477           (if (nnimap-ver4-p)
478               (mapconcat (lambda (part)
479                            (format "BODY.PEEK[%s]" part))
480                          parts " ")
481             (mapconcat (lambda (part)
482                          (format "RFC822.PEEK[%s]" part))
483                        parts " ")))))
484     (when result
485       (nnimap-convert-partial-article structure))))
486
487 (defun nnimap-convert-partial-article (structure)
488   ;; First just skip past the headers.
489   (goto-char (point-min))
490   (let ((bytes (nnimap-get-length))
491         id parts)
492     ;; Delete "FETCH" line.
493     (delete-region (line-beginning-position)
494                    (progn (forward-line 1) (point)))
495     (goto-char (+ (point) bytes))
496     ;; Collect all the body parts.
497     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
498       (setq id (match-string 1)
499             bytes (nnimap-get-length))
500       (beginning-of-line)
501       (delete-region (point) (progn (forward-line 1) (point)))
502       (push (list id (buffer-substring (point) (+ (point) bytes)))
503             parts)
504       (delete-region (point) (+ (point) bytes)))
505     ;; Delete trailing junk.
506     (delete-region (point) (point-max))
507     ;; Now insert all the parts again where they fit in the structure.
508     (nnimap-insert-partial-structure structure parts)
509     t))
510
511 (defun nnimap-insert-partial-structure (structure parts &optional subp)
512   (let ((type (car (last structure 4)))
513         (boundary (let ((bstruc structure))
514                     (while (consp (car bstruc))
515                       (pop bstruc))
516                     (setq bstruc (car (cdr bstruc)))
517                     (and (stringp (car bstruc))
518                          (string= (downcase (car bstruc)) "boundary")
519                          (cadr bstruc)))))
520     (when subp
521       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
522                       (downcase type) boundary)))
523     (while (not (stringp (car structure)))
524       (insert "\n--" boundary "\n")
525       (if (consp (caar structure))
526           (nnimap-insert-partial-structure (pop structure) parts t)
527         (let ((bit (pop structure)))
528           (insert (format  "Content-type: %s/%s"
529                            (downcase (nth 0 bit))
530                            (downcase (nth 1 bit))))
531           (if (member "CHARSET" (nth 2 bit))
532               (insert (format
533                        "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
534             (insert "\n"))
535           (insert (format "Content-transfer-encoding: %s\n"
536                           (nth 5 bit)))
537           (insert "\n")
538           (when (assoc (nth 9 bit) parts)
539             (insert (cadr (assoc (nth 9 bit) parts)))))))
540     (insert "\n--" boundary "--\n")))
541
542 (defun nnimap-find-wanted-parts (structure)
543   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
544
545 (defun nnimap-find-wanted-parts-1 (structure prefix)
546   (let ((num 1)
547         parts)
548     (while (consp (car structure))
549       (let ((sub (pop structure)))
550         (if (consp (car sub))
551             (push (nnimap-find-wanted-parts-1
552                    sub (if (string= prefix "")
553                            (number-to-string num)
554                          (format "%s.%s" prefix num)))
555                   parts)
556           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
557                 (id (if (string= prefix "")
558                         (number-to-string num)
559                       (format "%s.%s" prefix num))))
560             (setcar (nthcdr 9 sub) id)
561             (when (if (eq nnimap-fetch-partial-articles t)
562                       (equal id "1")
563                     (string-match nnimap-fetch-partial-articles type))
564               (push id parts))))
565         (incf num)))
566     (nreverse parts)))
567
568 (deffoo nnimap-request-group (group &optional server dont-check info)
569   (let ((result (nnimap-possibly-change-group group server))
570         articles active marks high low)
571     (with-current-buffer nntp-server-buffer
572       (when result
573         (if (and dont-check
574                  (setq active (nth 2 (assoc group nnimap-current-infos))))
575             (insert (format "211 %d %d %d %S\n"
576                             (- (cdr active) (car active))
577                             (car active)
578                             (cdr active)
579                             group))
580           (with-current-buffer (nnimap-buffer)
581             (erase-buffer)
582             (let ((group-sequence
583                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
584                   (flag-sequence
585                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
586               (nnimap-wait-for-response flag-sequence)
587               (setq marks
588                     (nnimap-flags-to-marks
589                      (nnimap-parse-flags
590                       (list (list group-sequence flag-sequence 1 group)))))
591               (when info
592                 (nnimap-update-infos marks (list info)))
593               (goto-char (point-max))
594               (let ((uidnext (nth 5 (car marks))))
595                 (setq high (if uidnext
596                                (1- uidnext)
597                              (nth 3 (car marks)))
598                       low (or (nth 4 (car marks)) uidnext)))))
599           (erase-buffer)
600           (insert
601            (format
602             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
603         t))))
604
605 (deffoo nnimap-request-create-group (group &optional server args)
606   (when (nnimap-possibly-change-group nil server)
607     (with-current-buffer (nnimap-buffer)
608       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
609
610 (deffoo nnimap-request-delete-group (group &optional force server)
611   (when (nnimap-possibly-change-group nil server)
612     (with-current-buffer (nnimap-buffer)
613       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
614
615 (deffoo nnimap-request-expunge-group (group &optional server)
616   (when (nnimap-possibly-change-group group server)
617     (with-current-buffer (nnimap-buffer)
618       (car (nnimap-command "EXPUNGE")))))
619
620 (defun nnimap-get-flags (spec)
621   (let ((articles nil)
622         elems)
623     (with-current-buffer (nnimap-buffer)
624       (erase-buffer)
625       (nnimap-wait-for-response (nnimap-send-command
626                                  "UID FETCH %s FLAGS" spec))
627       (goto-char (point-min))
628       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
629         (setq elems (nnimap-parse-line (match-string 1)))
630         (push (cons (string-to-number (cadr (member "UID" elems)))
631                     (cadr (member "FLAGS" elems)))
632               articles)))
633     (nreverse articles)))
634
635 (deffoo nnimap-close-group (group &optional server)
636   t)
637
638 (deffoo nnimap-request-move-article (article group server accept-form
639                                              &optional last internal-move-group)
640   (with-temp-buffer
641     (when (nnimap-request-article article group server (current-buffer))
642       ;; If the move is internal (on the same server), just do it the easy
643       ;; way.
644       (let ((message-id (message-field-value "message-id")))
645         (if internal-move-group
646             (let ((result
647                    (with-current-buffer (nnimap-buffer)
648                      (nnimap-command "UID COPY %d %S"
649                                      article
650                                      (utf7-encode internal-move-group t)))))
651               (when (car result)
652                 (nnimap-delete-article article)
653                 (cons internal-move-group
654                       (nnimap-find-article-by-message-id
655                        internal-move-group message-id))))
656           ;; Move the article to a different method.
657           (let ((result (eval accept-form)))
658             (when result
659               (nnimap-delete-article article)
660               result)))))))
661
662 (deffoo nnimap-request-expire-articles (articles group &optional server force)
663   (cond
664    ((null articles)
665     nil)
666    ((not (nnimap-possibly-change-group group server))
667     articles)
668    ((and force
669          (eq nnmail-expiry-target 'delete))
670     (unless (nnimap-delete-article (gnus-compress-sequence articles))
671       (message "Article marked for deletion, but not expunged."))
672     nil)
673    (t
674     (let ((deletable-articles
675            (if (or force
676                    (eq nnmail-expiry-wait 'immediate))
677                articles
678              (gnus-sorted-intersection
679               articles
680               (nnimap-find-expired-articles group)))))
681       (if (null deletable-articles)
682           articles
683         (if (eq nnmail-expiry-target 'delete)
684             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
685           (setq deletable-articles
686                 (nnimap-process-expiry-targets
687                  deletable-articles group server)))
688         ;; Return the articles we didn't delete.
689         (gnus-sorted-complement articles deletable-articles))))))
690
691 (defun nnimap-process-expiry-targets (articles group server)
692   (let ((deleted-articles nil))
693     (dolist (article articles)
694       (let ((target nnmail-expiry-target))
695         (with-temp-buffer
696           (when (nnimap-request-article article group server (current-buffer))
697             (message "Expiring article %s:%d" group article)
698             (when (functionp target)
699               (setq target (funcall target group)))
700             (when (and target
701                        (not (eq target 'delete)))
702               (if (or (gnus-request-group target t)
703                       (gnus-request-create-group target))
704                   (nnmail-expiry-target-group target group)
705                 (setq target nil)))
706             (when target
707               (push article deleted-articles))))))
708     ;; Change back to the current group again.
709     (nnimap-possibly-change-group group server)
710     (setq deleted-articles (nreverse deleted-articles))
711     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
712     deleted-articles))
713
714 (defun nnimap-find-expired-articles (group)
715   (let ((cutoff (nnmail-expired-article-p group nil nil)))
716     (with-current-buffer (nnimap-buffer)
717       (let ((result
718              (nnimap-command
719               "UID SEARCH SENTBEFORE %s"
720               (format-time-string
721                (format "%%d-%s-%%Y"
722                        (upcase
723                         (car (rassoc (nth 4 (decode-time cutoff))
724                                      parse-time-months))))
725                cutoff))))
726         (and (car result)
727              (delete 0 (mapcar #'string-to-number
728                                (cdr (assoc "SEARCH" (cdr result))))))))))
729
730
731 (defun nnimap-find-article-by-message-id (group message-id)
732   (when (nnimap-possibly-change-group group nil)
733     (with-current-buffer (nnimap-buffer)
734       (let ((result
735              (nnimap-command "UID SEARCH HEADER Message-Id %S" message-id))
736             article)
737         (when (car result)
738           ;; Select the last instance of the message in the group.
739           (and (setq article
740                      (car (last (assoc "SEARCH" (cdr result)))))
741                (string-to-number article)))))))
742
743 (defun nnimap-delete-article (articles)
744   (with-current-buffer (nnimap-buffer)
745     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
746                     (nnimap-article-ranges articles))
747     (cond
748      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
749       (nnimap-command "UID EXPUNGE %s"
750                       (nnimap-article-ranges articles))
751       t)
752      (nnimap-expunge
753       (nnimap-command "EXPUNGE")
754       t)
755      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
756                                 "server doesn't support UIDPLUS, so we won't "
757                                 "delete this article now"))))))
758
759 (deffoo nnimap-request-scan (&optional group server)
760   (when (and (nnimap-possibly-change-group nil server)
761              nnimap-inbox
762              nnimap-split-methods)
763     (message "nnimap %s splitting mail..." server)
764     (nnimap-split-incoming-mail)))
765
766 (defun nnimap-marks-to-flags (marks)
767   (let (flags flag)
768     (dolist (mark marks)
769       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
770         (push flag flags)))
771     flags))
772
773 (deffoo nnimap-request-set-mark (group actions &optional server)
774   (when (nnimap-possibly-change-group group server)
775     (let (sequence)
776       (with-current-buffer (nnimap-buffer)
777         ;; Just send all the STORE commands without waiting for
778         ;; response.  If they're successful, they're successful.
779         (dolist (action actions)
780           (destructuring-bind (range action marks) action
781             (let ((flags (nnimap-marks-to-flags marks)))
782               (when flags
783                 (setq sequence (nnimap-send-command
784                                 "UID STORE %s %sFLAGS.SILENT (%s)"
785                                 (nnimap-article-ranges range)
786                                 (if (eq action 'del)
787                                     "-"
788                                   "+")
789                                 (mapconcat #'identity flags " ")))))))
790         ;; Wait for the last command to complete to avoid later
791         ;; syncronisation problems with the stream.
792         (when sequence
793           (nnimap-wait-for-response sequence))))))
794
795 (deffoo nnimap-request-accept-article (group &optional server last)
796   (when (nnimap-possibly-change-group nil server)
797     (nnmail-check-syntax)
798     (nnimap-add-cr)
799     (let ((message (buffer-string))
800           (message-id (message-field-value "message-id"))
801           sequence)
802       (with-current-buffer (nnimap-buffer)
803         (setq sequence (nnimap-send-command
804                         "APPEND %S {%d}" (utf7-encode group t)
805                         (length message)))
806         (process-send-string (get-buffer-process (current-buffer)) message)
807         (process-send-string (get-buffer-process (current-buffer))
808                              (if (nnimap-newlinep nnimap-object)
809                                  "\n"
810                                "\r\n"))
811         (let ((result (nnimap-get-response sequence)))
812           (if (not (car result))
813               (progn
814                 (message "%s" (nnheader-get-report-string 'nnimap))
815                 nil)
816             (cons group
817                   (nnimap-find-article-by-message-id group message-id))))))))
818
819 (defun nnimap-add-cr ()
820   (goto-char (point-min))
821   (while (re-search-forward "\r?\n" nil t)
822     (replace-match "\r\n" t t)))
823
824 (defun nnimap-get-groups ()
825   (let ((result (nnimap-command "LIST \"\" \"*\""))
826         groups)
827     (when (car result)
828       (dolist (line (cdr result))
829         (when (and (equal (car line) "LIST")
830                    (not (and (caadr line)
831                              (string-match "noselect" (caadr line)))))
832           (push (car (last line)) groups)))
833       (nreverse groups))))
834
835 (deffoo nnimap-request-list (&optional server)
836   (nnimap-possibly-change-group nil server)
837   (with-current-buffer nntp-server-buffer
838     (erase-buffer)
839     (let ((groups
840            (with-current-buffer (nnimap-buffer)
841              (nnimap-get-groups)))
842           sequences responses)
843       (when groups
844         (with-current-buffer (nnimap-buffer)
845           (setf (nnimap-group nnimap-object) nil)
846           (dolist (group groups)
847             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
848                         group)
849                   sequences))
850           (nnimap-wait-for-response (caar sequences))
851           (setq responses
852                 (nnimap-get-responses (mapcar #'car sequences))))
853         (dolist (response responses)
854           (let* ((sequence (car response))
855                  (response (cadr response))
856                  (group (cadr (assoc sequence sequences))))
857             (when (and group
858                        (equal (caar response) "OK"))
859               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
860                     highest exists)
861                 (dolist (elem response)
862                   (when (equal (cadr elem) "EXISTS")
863                     (setq exists (string-to-number (car elem)))))
864                 (when uidnext
865                   (setq highest (1- (string-to-number (car uidnext)))))
866                 (cond
867                  ((null highest)
868                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
869                  ((zerop exists)
870                   ;; Empty group.
871                   (insert (format "%S %d %d y\n"
872                                   (utf7-decode group t) highest (1+ highest))))
873                  (t
874                   ;; Return the widest possible range.
875                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
876                                   (or highest exists)))))))))
877         t))))
878
879 (deffoo nnimap-retrieve-group-data-early (server infos)
880   (when (nnimap-possibly-change-group nil server)
881     (with-current-buffer (nnimap-buffer)
882       ;; QRESYNC handling isn't implemented.
883       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
884             marks groups sequences)
885         ;; Go through the infos and gather the data needed to know
886         ;; what and how to request the data.
887         (dolist (info infos)
888           (setq marks (gnus-info-marks info))
889           (push (list (gnus-group-real-name (gnus-info-group info))
890                       (cdr (assq 'active marks))
891                       (cdr (assq 'uid marks)))
892                 groups))
893         ;; Then request the data.
894         (erase-buffer)
895         (setf (nnimap-group nnimap-object) nil)
896         (dolist (elem groups)
897           (if (and qresyncp
898                    (nth 2 elem))
899               (push
900                (list 'qresync
901                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
902                                           (car elem)
903                                           (car (nth 2 elem))
904                                           (cdr (nth 2 elem)))
905                      nil
906                      (car elem))
907                sequences)
908             (let ((start
909                    (if (nth 1 elem)
910                        ;; Fetch the last 100 flags.
911                        (max 1 (- (cdr (nth 1 elem)) 100))
912                      1)))
913               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
914                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
915                           start
916                           (car elem))
917                     sequences)))
918           ;; Some servers apparently can't have many outstanding
919           ;; commands, so throttle them.
920           (when (and (not nnimap-streaming)
921                      (car sequences))
922             (nnimap-wait-for-response (caar sequences))))
923         sequences))))
924
925 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
926   (when (and sequences
927              (nnimap-possibly-change-group nil server))
928     (with-current-buffer (nnimap-buffer)
929       ;; Wait for the final data to trickle in.
930       (when (nnimap-wait-for-response (cadar sequences))
931         ;; Now we should have all the data we need, no matter whether
932         ;; we're QRESYNCING, fetching all the flags from scratch, or
933         ;; just fetching the last 100 flags per group.
934         (nnimap-update-infos (nnimap-flags-to-marks
935                               (nnimap-parse-flags
936                                (nreverse sequences)))
937                              infos)
938         ;; Finally, just return something resembling an active file in
939         ;; the nntp buffer, so that the agent can save the info, too.
940         (with-current-buffer nntp-server-buffer
941           (erase-buffer)
942           (dolist (info infos)
943             (let* ((group (gnus-info-group info))
944                    (active (gnus-active group)))
945               (when active
946                 (insert (format "%S %d %d y\n"
947                                 (gnus-group-real-name group)
948                                 (cdr active)
949                                 (car active)))))))))))
950
951 (defun nnimap-update-infos (flags infos)
952   (dolist (info infos)
953     (let ((group (gnus-group-real-name (gnus-info-group info))))
954       (nnimap-update-info info (cdr (assoc group flags))))))
955
956 (defun nnimap-update-info (info marks)
957   (when marks
958     (destructuring-bind (existing flags high low uidnext start-article
959                                   permanent-flags) marks
960       (let ((group (gnus-info-group info))
961             (completep (and start-article
962                             (= start-article 1))))
963         (when uidnext
964           (setq high (1- uidnext)))
965         ;; First set the active ranges based on high/low.
966         (if (or completep
967                 (not (gnus-active group)))
968             (gnus-set-active group
969                              (cond
970                               ((and low high)
971                                (cons low high))
972                               (uidnext
973                                ;; No articles in this group.
974                                (cons uidnext (1- uidnext)))
975                               (start-article
976                                (cons start-article (1- start-article)))
977                               (t
978                                ;; No articles and no uidnext.
979                                nil)))
980           (gnus-set-active
981            group
982            (cons (car (gnus-active group))
983                  (or high (1- uidnext)))))
984         (when (and (not high)
985                    uidnext)
986           (setq high (1- uidnext)))
987         ;; Then update the list of read articles.
988         (let* ((unread
989                 (gnus-compress-sequence
990                  (gnus-set-difference
991                   (gnus-set-difference
992                    existing
993                    (cdr (assoc '%Seen flags)))
994                   (cdr (assoc '%Flagged flags)))))
995                (read (gnus-range-difference
996                       (cons start-article high) unread)))
997           (when (> start-article 1)
998             (setq read
999                   (gnus-range-nconcat
1000                    (if (> start-article 1)
1001                        (gnus-sorted-range-intersection
1002                         (cons 1 (1- start-article))
1003                         (gnus-info-read info))
1004                      (gnus-info-read info))
1005                    read)))
1006           (gnus-info-set-read info read)
1007           ;; Update the marks.
1008           (setq marks (gnus-info-marks info))
1009           ;; Note the active level for the next run-through.
1010           (let ((active (assq 'active marks)))
1011             (if active
1012                 (setcdr active (gnus-active group))
1013               (push (cons 'active (gnus-active group)) marks)))
1014           (dolist (type (cdr nnimap-mark-alist))
1015             (let ((old-marks (assoc (car type) marks))
1016                   (new-marks
1017                    (gnus-compress-sequence
1018                     (cdr (or (assoc (caddr type) flags)     ; %Flagged
1019                              (assoc (intern (cadr type) obarray) flags)
1020                              (assoc (cadr type) flags)))))) ; "\Flagged"
1021               (setq marks (delq old-marks marks))
1022               (pop old-marks)
1023               (when (and old-marks
1024                          (> start-article 1))
1025                 (setq old-marks (gnus-range-difference
1026                                  old-marks
1027                                  (cons start-article high)))
1028                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1029               (when new-marks
1030                 (push (cons (car type) new-marks) marks)))
1031             (gnus-info-set-marks info marks t)
1032             (nnimap-store-info info (gnus-active group))))))))
1033
1034 (defun nnimap-store-info (info active)
1035   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1036          (entry (assoc group nnimap-current-infos)))
1037     (if entry
1038         (setcdr entry (list info active))
1039       (push (list group info active) nnimap-current-infos))))
1040
1041 (defun nnimap-flags-to-marks (groups)
1042   (let (data group totalp uidnext articles start-article mark permanent-flags)
1043     (dolist (elem groups)
1044       (setq group (car elem)
1045             uidnext (nth 1 elem)
1046             start-article (nth 2 elem)
1047             permanent-flags (nth 3 elem)
1048             articles (nthcdr 4 elem))
1049       (let ((high (caar articles))
1050             marks low existing)
1051         (dolist (article articles)
1052           (setq low (car article))
1053           (push (car article) existing)
1054           (dolist (flag (cdr article))
1055             (setq mark (assoc flag marks))
1056             (if (not mark)
1057                 (push (list flag (car article)) marks)
1058               (setcdr mark (cons (car article) (cdr mark))))))
1059         (push (list group existing marks high low uidnext start-article
1060                     permanent-flags)
1061               data)))
1062     data))
1063
1064 (defun nnimap-parse-flags (sequences)
1065   (goto-char (point-min))
1066   ;; Change \Delete etc to %Delete, so that the reader can read it.
1067   (subst-char-in-region (point-min) (point-max)
1068                         ?\\ ?% t)
1069   (let (start end articles groups uidnext elems permanent-flags)
1070     (dolist (elem sequences)
1071       (destructuring-bind (group-sequence flag-sequence totalp group) elem
1072         (setq start (point))
1073         ;; The EXAMINE was successful.
1074         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
1075                    (progn
1076                      (forward-line 1)
1077                      (setq end (point))
1078                      (goto-char start)
1079                      (setq permanent-flags
1080                            (and (search-forward "PERMANENTFLAGS "
1081                                                  (or end (point-min)) t)
1082                                 (read (current-buffer))))
1083                      (goto-char start)
1084                      (setq uidnext
1085                            (and (search-forward "UIDNEXT "
1086                                                  (or end (point-min)) t)
1087                                 (read (current-buffer))))
1088                      (goto-char end)
1089                      (forward-line -1))
1090                    ;; The UID FETCH FLAGS was successful.
1091                    (search-forward (format "\n%d OK " flag-sequence) nil t))
1092           (setq start (point))
1093           (goto-char end)
1094           (while (search-forward " FETCH " start t)
1095             (setq elems (read (current-buffer)))
1096             (push (cons (cadr (memq 'UID elems))
1097                         (cadr (memq 'FLAGS elems)))
1098                   articles))
1099           (push (nconc (list group uidnext totalp permanent-flags) articles)
1100                 groups)
1101           (setq articles nil))))
1102     groups))
1103
1104 (defun nnimap-find-process-buffer (buffer)
1105   (cadr (assoc buffer nnimap-connection-alist)))
1106
1107 (deffoo nnimap-request-post (&optional server)
1108   (setq nnimap-status-string "Read-only server")
1109   nil)
1110
1111 (defun nnimap-possibly-change-group (group server)
1112   (let ((open-result t))
1113     (when (and server
1114                (not (nnimap-server-opened server)))
1115       (setq open-result (nnimap-open-server server)))
1116     (cond
1117      ((not open-result)
1118       nil)
1119      ((not group)
1120       t)
1121      (t
1122       (with-current-buffer (nnimap-buffer)
1123         (if (equal group (nnimap-group nnimap-object))
1124             t
1125           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1126             (when (car result)
1127               (setf (nnimap-group nnimap-object) group
1128                     (nnimap-select-result nnimap-object) result)
1129               result))))))))
1130
1131 (defun nnimap-find-connection (buffer)
1132   "Find the connection delivering to BUFFER."
1133   (let ((entry (assoc buffer nnimap-connection-alist)))
1134     (when entry
1135       (if (and (buffer-name (cadr entry))
1136                (get-buffer-process (cadr entry))
1137                (memq (process-status (get-buffer-process (cadr entry)))
1138                      '(open run)))
1139           (get-buffer-process (cadr entry))
1140         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1141         nil))))
1142
1143 (defvar nnimap-sequence 0)
1144
1145 (defun nnimap-send-command (&rest args)
1146   (process-send-string
1147    (get-buffer-process (current-buffer))
1148    (nnimap-log-command
1149     (format "%d %s%s\n"
1150             (incf nnimap-sequence)
1151             (apply #'format args)
1152             (if (nnimap-newlinep nnimap-object)
1153                 ""
1154               "\r"))))
1155   nnimap-sequence)
1156
1157 (defun nnimap-log-command (command)
1158   (with-current-buffer (get-buffer-create "*imap log*")
1159     (goto-char (point-max))
1160     (insert (format-time-string "%H:%M:%S") " " command))
1161   command)
1162
1163 (defun nnimap-command (&rest args)
1164   (erase-buffer)
1165   (setf (nnimap-last-command-time nnimap-object) (current-time))
1166   (let* ((sequence (apply #'nnimap-send-command args))
1167          (response (nnimap-get-response sequence)))
1168     (if (equal (caar response) "OK")
1169         (cons t response)
1170       (nnheader-report 'nnimap "%s"
1171                        (mapconcat (lambda (a)
1172                                     (format "%s" a))
1173                                   (car response) " "))
1174       nil)))
1175
1176 (defun nnimap-get-response (sequence)
1177   (nnimap-wait-for-response sequence)
1178   (nnimap-parse-response))
1179
1180 (defun nnimap-wait-for-connection ()
1181   (let ((process (get-buffer-process (current-buffer))))
1182     (goto-char (point-min))
1183     (while (and (memq (process-status process)
1184                       '(open run))
1185                 (not (re-search-forward "^\\* .*\n" nil t)))
1186       (nnheader-accept-process-output process)
1187       (goto-char (point-min)))
1188     (forward-line -1)
1189     (and (looking-at "\\* \\([A-Z0-9]+\\)")
1190          (match-string 1))))
1191
1192 (defun nnimap-wait-for-response (sequence &optional messagep)
1193   (let ((process (get-buffer-process (current-buffer)))
1194         openp)
1195     (goto-char (point-max))
1196     (while (and (setq openp (memq (process-status process)
1197                                   '(open run)))
1198                 (not (re-search-backward
1199                       (format "^%d .*\n" sequence)
1200                       (if nnimap-streaming
1201                           (max (point-min) (- (point) 500))
1202                         (point-min))
1203                       t)))
1204       (when messagep
1205         (message "Read %dKB" (/ (buffer-size) 1000)))
1206       (nnheader-accept-process-output process)
1207       (goto-char (point-max)))
1208     openp))
1209
1210 (defun nnimap-parse-response ()
1211   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1212         result)
1213     (dolist (line lines)
1214       (push (cdr (nnimap-parse-line line)) result))
1215     ;; Return the OK/error code first, and then all the "continuation
1216     ;; lines" afterwards.
1217     (cons (pop result)
1218           (nreverse result))))
1219
1220 ;; Parse an IMAP response line lightly.  They look like
1221 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1222 ;; the lines into a list of strings and lists of string.
1223 (defun nnimap-parse-line (line)
1224   (let (char result)
1225     (with-temp-buffer
1226       (insert line)
1227       (goto-char (point-min))
1228       (while (not (eobp))
1229         (if (eql (setq char (following-char)) ? )
1230             (forward-char 1)
1231           (push
1232            (cond
1233             ((eql char ?\[)
1234              (split-string (buffer-substring
1235                             (1+ (point))
1236                             (1- (search-forward "]" (line-end-position) 'move)))))
1237             ((eql char ?\()
1238              (split-string (buffer-substring
1239                             (1+ (point))
1240                             (1- (search-forward ")" (line-end-position) 'move)))))
1241             ((eql char ?\")
1242              (forward-char 1)
1243              (buffer-substring
1244               (point)
1245               (1- (or (search-forward "\"" (line-end-position) 'move)
1246                       (point)))))
1247             (t
1248              (buffer-substring (point) (if (search-forward " " nil t)
1249                                            (1- (point))
1250                                          (goto-char (point-max))))))
1251            result)))
1252       (nreverse result))))
1253
1254 (defun nnimap-last-response-string ()
1255   (save-excursion
1256     (forward-line 1)
1257     (let ((end (point)))
1258       (forward-line -1)
1259       (when (not (bobp))
1260         (forward-line -1)
1261         (while (and (not (bobp))
1262                     (eql (following-char) ?*))
1263           (forward-line -1))
1264         (unless (eql (following-char) ?*)
1265           (forward-line 1)))
1266       (buffer-substring (point) end))))
1267
1268 (defun nnimap-get-responses (sequences)
1269   (let (responses)
1270     (dolist (sequence sequences)
1271       (goto-char (point-min))
1272       (when (re-search-forward (format "^%d " sequence) nil t)
1273         (push (list sequence (nnimap-parse-response))
1274               responses)))
1275     responses))
1276
1277 (defvar nnimap-incoming-split-list nil)
1278
1279 (defun nnimap-fetch-inbox (articles)
1280   (erase-buffer)
1281   (nnimap-wait-for-response
1282    (nnimap-send-command
1283     "UID FETCH %s %s"
1284     (nnimap-article-ranges articles)
1285     (format "(UID %s%s)"
1286             (format
1287              (if (nnimap-ver4-p)
1288                  "BODY.PEEK[HEADER] BODY.PEEK"
1289                "RFC822.PEEK"))
1290             (if nnimap-split-download-body-default
1291                 "[]"
1292               "[1]")))
1293    t))
1294
1295 (defun nnimap-split-incoming-mail ()
1296   (with-current-buffer (nnimap-buffer)
1297     (let ((nnimap-incoming-split-list nil)
1298           (nnmail-split-methods nnimap-split-methods)
1299           (nnmail-inhibit-default-split-group t)
1300           (groups (nnimap-get-groups))
1301           new-articles)
1302       (erase-buffer)
1303       (nnimap-command "SELECT %S" nnimap-inbox)
1304       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1305       (when new-articles
1306         (nnimap-fetch-inbox new-articles)
1307         (nnimap-transform-split-mail)
1308         (nnheader-ms-strip-cr)
1309         (nnmail-cache-open)
1310         (nnmail-split-incoming (current-buffer)
1311                                #'nnimap-save-mail-spec
1312                                nil nil
1313                                #'nnimap-dummy-active-number
1314                                #'nnimap-save-mail-spec)
1315         (when nnimap-incoming-split-list
1316           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1317                 sequences junk-articles)
1318             ;; Create any groups that doesn't already exist on the
1319             ;; server first.
1320             (dolist (spec specs)
1321               (when (and (not (member (car spec) groups))
1322                          (not (eq (car spec) 'junk)))
1323                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1324             ;; Then copy over all the messages.
1325             (erase-buffer)
1326             (dolist (spec specs)
1327               (let ((group (car spec))
1328                     (ranges (cdr spec)))
1329                 (if (eq group 'junk)
1330                     (setq junk-articles ranges)
1331                   (push (list (nnimap-send-command
1332                                "UID COPY %s %S"
1333                                (nnimap-article-ranges ranges)
1334                                (utf7-encode group t))
1335                               ranges)
1336                         sequences))))
1337             ;; Wait for the last COPY response...
1338             (when sequences
1339               (nnimap-wait-for-response (caar sequences))
1340               ;; And then mark the successful copy actions as deleted,
1341               ;; and possibly expunge them.
1342               (nnimap-mark-and-expunge-incoming
1343                (nnimap-parse-copied-articles sequences)))
1344             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1345
1346 (defun nnimap-mark-and-expunge-incoming (range)
1347   (when range
1348     (setq range (nnimap-article-ranges range))
1349     (let ((sequence
1350            (nnimap-send-command
1351             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1352       (cond
1353        ;; If the server supports it, we now delete the message we have
1354        ;; just copied over.
1355        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1356         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1357        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1358        ;; user has configured it.
1359        (nnimap-expunge
1360         (setq sequence (nnimap-send-command "EXPUNGE"))))
1361       (nnimap-wait-for-response sequence))))
1362
1363 (defun nnimap-parse-copied-articles (sequences)
1364   (let (sequence copied range)
1365     (goto-char (point-min))
1366     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1367       (setq sequence (string-to-number (match-string 1)))
1368       (when (setq range (cadr (assq sequence sequences)))
1369         (push (gnus-uncompress-range range) copied)))
1370     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1371
1372 (defun nnimap-new-articles (flags)
1373   (let (new)
1374     (dolist (elem flags)
1375       (when (or (null (cdr elem))
1376                 (and (not (memq '%Deleted (cdr elem)))
1377                      (not (memq '%Seen (cdr elem)))))
1378         (push (car elem) new)))
1379     (gnus-compress-sequence (nreverse new))))
1380
1381 (defun nnimap-make-split-specs (list)
1382   (let ((specs nil)
1383         entry)
1384     (dolist (elem list)
1385       (destructuring-bind (article spec) elem
1386         (dolist (group (delete nil (mapcar #'car spec)))
1387           (unless (setq entry (assoc group specs))
1388             (push (setq entry (list group)) specs))
1389           (setcdr entry (cons article (cdr entry))))))
1390     (dolist (entry specs)
1391       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1392     specs))
1393
1394 (defun nnimap-transform-split-mail ()
1395   (goto-char (point-min))
1396   (let (article bytes)
1397     (block nil
1398       (while (not (eobp))
1399         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1400           (delete-region (point) (progn (forward-line 1) (point)))
1401           (when (eobp)
1402             (return)))
1403         (setq article (match-string 1)
1404               bytes (nnimap-get-length))
1405         (delete-region (line-beginning-position) (line-end-position))
1406         ;; Insert MMDF separator, and a way to remember what this
1407         ;; article UID is.
1408         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1409         (forward-char (1+ bytes))
1410         (setq bytes (nnimap-get-length))
1411         (delete-region (line-beginning-position) (line-end-position))
1412         (forward-char (1+ bytes))
1413         (delete-region (line-beginning-position) (line-end-position))))))
1414
1415 (defun nnimap-dummy-active-number (group &optional server)
1416   1)
1417
1418 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1419   (let (article)
1420     (goto-char (point-min))
1421     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1422         (error "Invalid nnimap mail")
1423       (setq article (string-to-number (match-string 1))))
1424     (push (list article
1425                 (if (eq group-art 'junk)
1426                     (list (cons 'junk 1))
1427                   group-art))
1428           nnimap-incoming-split-list)))
1429
1430 (provide 'nnimap)
1431
1432 ;;; nnimap.el ends here