(nnimap-insert-partial-structure): Get the type from the correct slot, too.
[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 boundary)
513     (let ((bstruc structure))
514       (while (consp (car bstruc))
515         (pop bstruc))
516       (setq type (car bstruc))
517       (setq bstruc (car (cdr bstruc)))
518       (when (and (stringp (car bstruc))
519                  (string= (downcase (car bstruc)) "boundary"))
520         (setq boundary (cadr bstruc))))
521     (when subp
522       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
523                       (downcase type) boundary)))
524     (while (not (stringp (car structure)))
525       (insert "\n--" boundary "\n")
526       (if (consp (caar structure))
527           (nnimap-insert-partial-structure (pop structure) parts t)
528         (let ((bit (pop structure)))
529           (insert (format  "Content-type: %s/%s"
530                            (downcase (nth 0 bit))
531                            (downcase (nth 1 bit))))
532           (if (member "CHARSET" (nth 2 bit))
533               (insert (format
534                        "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
535             (insert "\n"))
536           (insert (format "Content-transfer-encoding: %s\n"
537                           (nth 5 bit)))
538           (insert "\n")
539           (when (assoc (nth 9 bit) parts)
540             (insert (cadr (assoc (nth 9 bit) parts)))))))
541     (insert "\n--" boundary "--\n")))
542
543 (defun nnimap-find-wanted-parts (structure)
544   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
545
546 (defun nnimap-find-wanted-parts-1 (structure prefix)
547   (let ((num 1)
548         parts)
549     (while (consp (car structure))
550       (let ((sub (pop structure)))
551         (if (consp (car sub))
552             (push (nnimap-find-wanted-parts-1
553                    sub (if (string= prefix "")
554                            (number-to-string num)
555                          (format "%s.%s" prefix num)))
556                   parts)
557           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
558                 (id (if (string= prefix "")
559                         (number-to-string num)
560                       (format "%s.%s" prefix num))))
561             (setcar (nthcdr 9 sub) id)
562             (when (if (eq nnimap-fetch-partial-articles t)
563                       (equal id "1")
564                     (string-match nnimap-fetch-partial-articles type))
565               (push id parts))))
566         (incf num)))
567     (nreverse parts)))
568
569 (deffoo nnimap-request-group (group &optional server dont-check info)
570   (let ((result (nnimap-possibly-change-group group server))
571         articles active marks high low)
572     (with-current-buffer nntp-server-buffer
573       (when result
574         (if (and dont-check
575                  (setq active (nth 2 (assoc group nnimap-current-infos))))
576             (insert (format "211 %d %d %d %S\n"
577                             (- (cdr active) (car active))
578                             (car active)
579                             (cdr active)
580                             group))
581           (with-current-buffer (nnimap-buffer)
582             (erase-buffer)
583             (let ((group-sequence
584                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
585                   (flag-sequence
586                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
587               (nnimap-wait-for-response flag-sequence)
588               (setq marks
589                     (nnimap-flags-to-marks
590                      (nnimap-parse-flags
591                       (list (list group-sequence flag-sequence 1 group)))))
592               (when info
593                 (nnimap-update-infos marks (list info)))
594               (goto-char (point-max))
595               (let ((uidnext (nth 5 (car marks))))
596                 (setq high (if uidnext
597                                (1- uidnext)
598                              (nth 3 (car marks)))
599                       low (or (nth 4 (car marks)) uidnext)))))
600           (erase-buffer)
601           (insert
602            (format
603             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
604         t))))
605
606 (deffoo nnimap-request-create-group (group &optional server args)
607   (when (nnimap-possibly-change-group nil server)
608     (with-current-buffer (nnimap-buffer)
609       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
610
611 (deffoo nnimap-request-delete-group (group &optional force server)
612   (when (nnimap-possibly-change-group nil server)
613     (with-current-buffer (nnimap-buffer)
614       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
615
616 (deffoo nnimap-request-expunge-group (group &optional server)
617   (when (nnimap-possibly-change-group group server)
618     (with-current-buffer (nnimap-buffer)
619       (car (nnimap-command "EXPUNGE")))))
620
621 (defun nnimap-get-flags (spec)
622   (let ((articles nil)
623         elems)
624     (with-current-buffer (nnimap-buffer)
625       (erase-buffer)
626       (nnimap-wait-for-response (nnimap-send-command
627                                  "UID FETCH %s FLAGS" spec))
628       (goto-char (point-min))
629       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
630         (setq elems (nnimap-parse-line (match-string 1)))
631         (push (cons (string-to-number (cadr (member "UID" elems)))
632                     (cadr (member "FLAGS" elems)))
633               articles)))
634     (nreverse articles)))
635
636 (deffoo nnimap-close-group (group &optional server)
637   t)
638
639 (deffoo nnimap-request-move-article (article group server accept-form
640                                              &optional last internal-move-group)
641   (with-temp-buffer
642     (when (nnimap-request-article article group server (current-buffer))
643       ;; If the move is internal (on the same server), just do it the easy
644       ;; way.
645       (let ((message-id (message-field-value "message-id")))
646         (if internal-move-group
647             (let ((result
648                    (with-current-buffer (nnimap-buffer)
649                      (nnimap-command "UID COPY %d %S"
650                                      article
651                                      (utf7-encode internal-move-group t)))))
652               (when (car result)
653                 (nnimap-delete-article article)
654                 (cons internal-move-group
655                       (nnimap-find-article-by-message-id
656                        internal-move-group message-id))))
657           ;; Move the article to a different method.
658           (let ((result (eval accept-form)))
659             (when result
660               (nnimap-delete-article article)
661               result)))))))
662
663 (deffoo nnimap-request-expire-articles (articles group &optional server force)
664   (cond
665    ((null articles)
666     nil)
667    ((not (nnimap-possibly-change-group group server))
668     articles)
669    ((and force
670          (eq nnmail-expiry-target 'delete))
671     (unless (nnimap-delete-article (gnus-compress-sequence articles))
672       (message "Article marked for deletion, but not expunged."))
673     nil)
674    (t
675     (let ((deletable-articles
676            (if (or force
677                    (eq nnmail-expiry-wait 'immediate))
678                articles
679              (gnus-sorted-intersection
680               articles
681               (nnimap-find-expired-articles group)))))
682       (if (null deletable-articles)
683           articles
684         (if (eq nnmail-expiry-target 'delete)
685             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
686           (setq deletable-articles
687                 (nnimap-process-expiry-targets
688                  deletable-articles group server)))
689         ;; Return the articles we didn't delete.
690         (gnus-sorted-complement articles deletable-articles))))))
691
692 (defun nnimap-process-expiry-targets (articles group server)
693   (let ((deleted-articles nil))
694     (dolist (article articles)
695       (let ((target nnmail-expiry-target))
696         (with-temp-buffer
697           (when (nnimap-request-article article group server (current-buffer))
698             (message "Expiring article %s:%d" group article)
699             (when (functionp target)
700               (setq target (funcall target group)))
701             (when (and target
702                        (not (eq target 'delete)))
703               (if (or (gnus-request-group target t)
704                       (gnus-request-create-group target))
705                   (nnmail-expiry-target-group target group)
706                 (setq target nil)))
707             (when target
708               (push article deleted-articles))))))
709     ;; Change back to the current group again.
710     (nnimap-possibly-change-group group server)
711     (setq deleted-articles (nreverse deleted-articles))
712     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
713     deleted-articles))
714
715 (defun nnimap-find-expired-articles (group)
716   (let ((cutoff (nnmail-expired-article-p group nil nil)))
717     (with-current-buffer (nnimap-buffer)
718       (let ((result
719              (nnimap-command
720               "UID SEARCH SENTBEFORE %s"
721               (format-time-string
722                (format "%%d-%s-%%Y"
723                        (upcase
724                         (car (rassoc (nth 4 (decode-time cutoff))
725                                      parse-time-months))))
726                cutoff))))
727         (and (car result)
728              (delete 0 (mapcar #'string-to-number
729                                (cdr (assoc "SEARCH" (cdr result))))))))))
730
731
732 (defun nnimap-find-article-by-message-id (group message-id)
733   (when (nnimap-possibly-change-group group nil)
734     (with-current-buffer (nnimap-buffer)
735       (let ((result
736              (nnimap-command "UID SEARCH HEADER Message-Id %S" message-id))
737             article)
738         (when (car result)
739           ;; Select the last instance of the message in the group.
740           (and (setq article
741                      (car (last (assoc "SEARCH" (cdr result)))))
742                (string-to-number article)))))))
743
744 (defun nnimap-delete-article (articles)
745   (with-current-buffer (nnimap-buffer)
746     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
747                     (nnimap-article-ranges articles))
748     (cond
749      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
750       (nnimap-command "UID EXPUNGE %s"
751                       (nnimap-article-ranges articles))
752       t)
753      (nnimap-expunge
754       (nnimap-command "EXPUNGE")
755       t)
756      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
757                                 "server doesn't support UIDPLUS, so we won't "
758                                 "delete this article now"))))))
759
760 (deffoo nnimap-request-scan (&optional group server)
761   (when (and (nnimap-possibly-change-group nil server)
762              nnimap-inbox
763              nnimap-split-methods)
764     (message "nnimap %s splitting mail..." server)
765     (nnimap-split-incoming-mail)))
766
767 (defun nnimap-marks-to-flags (marks)
768   (let (flags flag)
769     (dolist (mark marks)
770       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
771         (push flag flags)))
772     flags))
773
774 (deffoo nnimap-request-set-mark (group actions &optional server)
775   (when (nnimap-possibly-change-group group server)
776     (let (sequence)
777       (with-current-buffer (nnimap-buffer)
778         ;; Just send all the STORE commands without waiting for
779         ;; response.  If they're successful, they're successful.
780         (dolist (action actions)
781           (destructuring-bind (range action marks) action
782             (let ((flags (nnimap-marks-to-flags marks)))
783               (when flags
784                 (setq sequence (nnimap-send-command
785                                 "UID STORE %s %sFLAGS.SILENT (%s)"
786                                 (nnimap-article-ranges range)
787                                 (if (eq action 'del)
788                                     "-"
789                                   "+")
790                                 (mapconcat #'identity flags " ")))))))
791         ;; Wait for the last command to complete to avoid later
792         ;; syncronisation problems with the stream.
793         (when sequence
794           (nnimap-wait-for-response sequence))))))
795
796 (deffoo nnimap-request-accept-article (group &optional server last)
797   (when (nnimap-possibly-change-group nil server)
798     (nnmail-check-syntax)
799     (nnimap-add-cr)
800     (let ((message (buffer-string))
801           (message-id (message-field-value "message-id"))
802           sequence)
803       (with-current-buffer (nnimap-buffer)
804         (setq sequence (nnimap-send-command
805                         "APPEND %S {%d}" (utf7-encode group t)
806                         (length message)))
807         (process-send-string (get-buffer-process (current-buffer)) message)
808         (process-send-string (get-buffer-process (current-buffer))
809                              (if (nnimap-newlinep nnimap-object)
810                                  "\n"
811                                "\r\n"))
812         (let ((result (nnimap-get-response sequence)))
813           (if (not (car result))
814               (progn
815                 (message "%s" (nnheader-get-report-string 'nnimap))
816                 nil)
817             (cons group
818                   (nnimap-find-article-by-message-id group message-id))))))))
819
820 (defun nnimap-add-cr ()
821   (goto-char (point-min))
822   (while (re-search-forward "\r?\n" nil t)
823     (replace-match "\r\n" t t)))
824
825 (defun nnimap-get-groups ()
826   (let ((result (nnimap-command "LIST \"\" \"*\""))
827         groups)
828     (when (car result)
829       (dolist (line (cdr result))
830         (when (and (equal (car line) "LIST")
831                    (not (and (caadr line)
832                              (string-match "noselect" (caadr line)))))
833           (push (car (last line)) groups)))
834       (nreverse groups))))
835
836 (deffoo nnimap-request-list (&optional server)
837   (nnimap-possibly-change-group nil server)
838   (with-current-buffer nntp-server-buffer
839     (erase-buffer)
840     (let ((groups
841            (with-current-buffer (nnimap-buffer)
842              (nnimap-get-groups)))
843           sequences responses)
844       (when groups
845         (with-current-buffer (nnimap-buffer)
846           (setf (nnimap-group nnimap-object) nil)
847           (dolist (group groups)
848             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
849                         group)
850                   sequences))
851           (nnimap-wait-for-response (caar sequences))
852           (setq responses
853                 (nnimap-get-responses (mapcar #'car sequences))))
854         (dolist (response responses)
855           (let* ((sequence (car response))
856                  (response (cadr response))
857                  (group (cadr (assoc sequence sequences))))
858             (when (and group
859                        (equal (caar response) "OK"))
860               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
861                     highest exists)
862                 (dolist (elem response)
863                   (when (equal (cadr elem) "EXISTS")
864                     (setq exists (string-to-number (car elem)))))
865                 (when uidnext
866                   (setq highest (1- (string-to-number (car uidnext)))))
867                 (cond
868                  ((null highest)
869                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
870                  ((zerop exists)
871                   ;; Empty group.
872                   (insert (format "%S %d %d y\n"
873                                   (utf7-decode group t) highest (1+ highest))))
874                  (t
875                   ;; Return the widest possible range.
876                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
877                                   (or highest exists)))))))))
878         t))))
879
880 (deffoo nnimap-retrieve-group-data-early (server infos)
881   (when (nnimap-possibly-change-group nil server)
882     (with-current-buffer (nnimap-buffer)
883       ;; QRESYNC handling isn't implemented.
884       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
885             marks groups sequences)
886         ;; Go through the infos and gather the data needed to know
887         ;; what and how to request the data.
888         (dolist (info infos)
889           (setq marks (gnus-info-marks info))
890           (push (list (gnus-group-real-name (gnus-info-group info))
891                       (cdr (assq 'active marks))
892                       (cdr (assq 'uid marks)))
893                 groups))
894         ;; Then request the data.
895         (erase-buffer)
896         (setf (nnimap-group nnimap-object) nil)
897         (dolist (elem groups)
898           (if (and qresyncp
899                    (nth 2 elem))
900               (push
901                (list 'qresync
902                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
903                                           (car elem)
904                                           (car (nth 2 elem))
905                                           (cdr (nth 2 elem)))
906                      nil
907                      (car elem))
908                sequences)
909             (let ((start
910                    (if (nth 1 elem)
911                        ;; Fetch the last 100 flags.
912                        (max 1 (- (cdr (nth 1 elem)) 100))
913                      1)))
914               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
915                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
916                           start
917                           (car elem))
918                     sequences)))
919           ;; Some servers apparently can't have many outstanding
920           ;; commands, so throttle them.
921           (when (and (not nnimap-streaming)
922                      (car sequences))
923             (nnimap-wait-for-response (caar sequences))))
924         sequences))))
925
926 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
927   (when (and sequences
928              (nnimap-possibly-change-group nil server))
929     (with-current-buffer (nnimap-buffer)
930       ;; Wait for the final data to trickle in.
931       (when (nnimap-wait-for-response (cadar sequences))
932         ;; Now we should have all the data we need, no matter whether
933         ;; we're QRESYNCING, fetching all the flags from scratch, or
934         ;; just fetching the last 100 flags per group.
935         (nnimap-update-infos (nnimap-flags-to-marks
936                               (nnimap-parse-flags
937                                (nreverse sequences)))
938                              infos)
939         ;; Finally, just return something resembling an active file in
940         ;; the nntp buffer, so that the agent can save the info, too.
941         (with-current-buffer nntp-server-buffer
942           (erase-buffer)
943           (dolist (info infos)
944             (let* ((group (gnus-info-group info))
945                    (active (gnus-active group)))
946               (when active
947                 (insert (format "%S %d %d y\n"
948                                 (gnus-group-real-name group)
949                                 (cdr active)
950                                 (car active)))))))))))
951
952 (defun nnimap-update-infos (flags infos)
953   (dolist (info infos)
954     (let ((group (gnus-group-real-name (gnus-info-group info))))
955       (nnimap-update-info info (cdr (assoc group flags))))))
956
957 (defun nnimap-update-info (info marks)
958   (when marks
959     (destructuring-bind (existing flags high low uidnext start-article
960                                   permanent-flags) marks
961       (let ((group (gnus-info-group info))
962             (completep (and start-article
963                             (= start-article 1))))
964         (when uidnext
965           (setq high (1- uidnext)))
966         ;; First set the active ranges based on high/low.
967         (if (or completep
968                 (not (gnus-active group)))
969             (gnus-set-active group
970                              (cond
971                               ((and low high)
972                                (cons low high))
973                               (uidnext
974                                ;; No articles in this group.
975                                (cons uidnext (1- uidnext)))
976                               (start-article
977                                (cons start-article (1- start-article)))
978                               (t
979                                ;; No articles and no uidnext.
980                                nil)))
981           (gnus-set-active
982            group
983            (cons (car (gnus-active group))
984                  (or high (1- uidnext)))))
985         (when (and (not high)
986                    uidnext)
987           (setq high (1- uidnext)))
988         ;; Then update the list of read articles.
989         (let* ((unread
990                 (gnus-compress-sequence
991                  (gnus-set-difference
992                   (gnus-set-difference
993                    existing
994                    (cdr (assoc '%Seen flags)))
995                   (cdr (assoc '%Flagged flags)))))
996                (read (gnus-range-difference
997                       (cons start-article high) unread)))
998           (when (> start-article 1)
999             (setq read
1000                   (gnus-range-nconcat
1001                    (if (> start-article 1)
1002                        (gnus-sorted-range-intersection
1003                         (cons 1 (1- start-article))
1004                         (gnus-info-read info))
1005                      (gnus-info-read info))
1006                    read)))
1007           (gnus-info-set-read info read)
1008           ;; Update the marks.
1009           (setq marks (gnus-info-marks info))
1010           ;; Note the active level for the next run-through.
1011           (let ((active (assq 'active marks)))
1012             (if active
1013                 (setcdr active (gnus-active group))
1014               (push (cons 'active (gnus-active group)) marks)))
1015           (dolist (type (cdr nnimap-mark-alist))
1016             (let ((old-marks (assoc (car type) marks))
1017                   (new-marks
1018                    (gnus-compress-sequence
1019                     (cdr (or (assoc (caddr type) flags)     ; %Flagged
1020                              (assoc (intern (cadr type) obarray) flags)
1021                              (assoc (cadr type) flags)))))) ; "\Flagged"
1022               (setq marks (delq old-marks marks))
1023               (pop old-marks)
1024               (when (and old-marks
1025                          (> start-article 1))
1026                 (setq old-marks (gnus-range-difference
1027                                  old-marks
1028                                  (cons start-article high)))
1029                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1030               (when new-marks
1031                 (push (cons (car type) new-marks) marks)))
1032             (gnus-info-set-marks info marks t)
1033             (nnimap-store-info info (gnus-active group))))))))
1034
1035 (defun nnimap-store-info (info active)
1036   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1037          (entry (assoc group nnimap-current-infos)))
1038     (if entry
1039         (setcdr entry (list info active))
1040       (push (list group info active) nnimap-current-infos))))
1041
1042 (defun nnimap-flags-to-marks (groups)
1043   (let (data group totalp uidnext articles start-article mark permanent-flags)
1044     (dolist (elem groups)
1045       (setq group (car elem)
1046             uidnext (nth 1 elem)
1047             start-article (nth 2 elem)
1048             permanent-flags (nth 3 elem)
1049             articles (nthcdr 4 elem))
1050       (let ((high (caar articles))
1051             marks low existing)
1052         (dolist (article articles)
1053           (setq low (car article))
1054           (push (car article) existing)
1055           (dolist (flag (cdr article))
1056             (setq mark (assoc flag marks))
1057             (if (not mark)
1058                 (push (list flag (car article)) marks)
1059               (setcdr mark (cons (car article) (cdr mark))))))
1060         (push (list group existing marks high low uidnext start-article
1061                     permanent-flags)
1062               data)))
1063     data))
1064
1065 (defun nnimap-parse-flags (sequences)
1066   (goto-char (point-min))
1067   ;; Change \Delete etc to %Delete, so that the reader can read it.
1068   (subst-char-in-region (point-min) (point-max)
1069                         ?\\ ?% t)
1070   (let (start end articles groups uidnext elems permanent-flags)
1071     (dolist (elem sequences)
1072       (destructuring-bind (group-sequence flag-sequence totalp group) elem
1073         (setq start (point))
1074         ;; The EXAMINE was successful.
1075         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
1076                    (progn
1077                      (forward-line 1)
1078                      (setq end (point))
1079                      (goto-char start)
1080                      (setq permanent-flags
1081                            (and (search-forward "PERMANENTFLAGS "
1082                                                  (or end (point-min)) t)
1083                                 (read (current-buffer))))
1084                      (goto-char start)
1085                      (setq uidnext
1086                            (and (search-forward "UIDNEXT "
1087                                                  (or end (point-min)) t)
1088                                 (read (current-buffer))))
1089                      (goto-char end)
1090                      (forward-line -1))
1091                    ;; The UID FETCH FLAGS was successful.
1092                    (search-forward (format "\n%d OK " flag-sequence) nil t))
1093           (setq start (point))
1094           (goto-char end)
1095           (while (search-forward " FETCH " start t)
1096             (setq elems (read (current-buffer)))
1097             (push (cons (cadr (memq 'UID elems))
1098                         (cadr (memq 'FLAGS elems)))
1099                   articles))
1100           (push (nconc (list group uidnext totalp permanent-flags) articles)
1101                 groups)
1102           (setq articles nil))))
1103     groups))
1104
1105 (defun nnimap-find-process-buffer (buffer)
1106   (cadr (assoc buffer nnimap-connection-alist)))
1107
1108 (deffoo nnimap-request-post (&optional server)
1109   (setq nnimap-status-string "Read-only server")
1110   nil)
1111
1112 (defun nnimap-possibly-change-group (group server)
1113   (let ((open-result t))
1114     (when (and server
1115                (not (nnimap-server-opened server)))
1116       (setq open-result (nnimap-open-server server)))
1117     (cond
1118      ((not open-result)
1119       nil)
1120      ((not group)
1121       t)
1122      (t
1123       (with-current-buffer (nnimap-buffer)
1124         (if (equal group (nnimap-group nnimap-object))
1125             t
1126           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1127             (when (car result)
1128               (setf (nnimap-group nnimap-object) group
1129                     (nnimap-select-result nnimap-object) result)
1130               result))))))))
1131
1132 (defun nnimap-find-connection (buffer)
1133   "Find the connection delivering to BUFFER."
1134   (let ((entry (assoc buffer nnimap-connection-alist)))
1135     (when entry
1136       (if (and (buffer-name (cadr entry))
1137                (get-buffer-process (cadr entry))
1138                (memq (process-status (get-buffer-process (cadr entry)))
1139                      '(open run)))
1140           (get-buffer-process (cadr entry))
1141         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1142         nil))))
1143
1144 (defvar nnimap-sequence 0)
1145
1146 (defun nnimap-send-command (&rest args)
1147   (process-send-string
1148    (get-buffer-process (current-buffer))
1149    (nnimap-log-command
1150     (format "%d %s%s\n"
1151             (incf nnimap-sequence)
1152             (apply #'format args)
1153             (if (nnimap-newlinep nnimap-object)
1154                 ""
1155               "\r"))))
1156   nnimap-sequence)
1157
1158 (defun nnimap-log-command (command)
1159   (with-current-buffer (get-buffer-create "*imap log*")
1160     (goto-char (point-max))
1161     (insert (format-time-string "%H:%M:%S") " " command))
1162   command)
1163
1164 (defun nnimap-command (&rest args)
1165   (erase-buffer)
1166   (setf (nnimap-last-command-time nnimap-object) (current-time))
1167   (let* ((sequence (apply #'nnimap-send-command args))
1168          (response (nnimap-get-response sequence)))
1169     (if (equal (caar response) "OK")
1170         (cons t response)
1171       (nnheader-report 'nnimap "%s"
1172                        (mapconcat (lambda (a)
1173                                     (format "%s" a))
1174                                   (car response) " "))
1175       nil)))
1176
1177 (defun nnimap-get-response (sequence)
1178   (nnimap-wait-for-response sequence)
1179   (nnimap-parse-response))
1180
1181 (defun nnimap-wait-for-connection ()
1182   (let ((process (get-buffer-process (current-buffer))))
1183     (goto-char (point-min))
1184     (while (and (memq (process-status process)
1185                       '(open run))
1186                 (not (re-search-forward "^\\* .*\n" nil t)))
1187       (nnheader-accept-process-output process)
1188       (goto-char (point-min)))
1189     (forward-line -1)
1190     (and (looking-at "\\* \\([A-Z0-9]+\\)")
1191          (match-string 1))))
1192
1193 (defun nnimap-wait-for-response (sequence &optional messagep)
1194   (let ((process (get-buffer-process (current-buffer)))
1195         openp)
1196     (goto-char (point-max))
1197     (while (and (setq openp (memq (process-status process)
1198                                   '(open run)))
1199                 (not (re-search-backward
1200                       (format "^%d .*\n" sequence)
1201                       (if nnimap-streaming
1202                           (max (point-min) (- (point) 500))
1203                         (point-min))
1204                       t)))
1205       (when messagep
1206         (message "Read %dKB" (/ (buffer-size) 1000)))
1207       (nnheader-accept-process-output process)
1208       (goto-char (point-max)))
1209     openp))
1210
1211 (defun nnimap-parse-response ()
1212   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1213         result)
1214     (dolist (line lines)
1215       (push (cdr (nnimap-parse-line line)) result))
1216     ;; Return the OK/error code first, and then all the "continuation
1217     ;; lines" afterwards.
1218     (cons (pop result)
1219           (nreverse result))))
1220
1221 ;; Parse an IMAP response line lightly.  They look like
1222 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1223 ;; the lines into a list of strings and lists of string.
1224 (defun nnimap-parse-line (line)
1225   (let (char result)
1226     (with-temp-buffer
1227       (insert line)
1228       (goto-char (point-min))
1229       (while (not (eobp))
1230         (if (eql (setq char (following-char)) ? )
1231             (forward-char 1)
1232           (push
1233            (cond
1234             ((eql char ?\[)
1235              (split-string (buffer-substring
1236                             (1+ (point))
1237                             (1- (search-forward "]" (line-end-position) 'move)))))
1238             ((eql char ?\()
1239              (split-string (buffer-substring
1240                             (1+ (point))
1241                             (1- (search-forward ")" (line-end-position) 'move)))))
1242             ((eql char ?\")
1243              (forward-char 1)
1244              (buffer-substring
1245               (point)
1246               (1- (or (search-forward "\"" (line-end-position) 'move)
1247                       (point)))))
1248             (t
1249              (buffer-substring (point) (if (search-forward " " nil t)
1250                                            (1- (point))
1251                                          (goto-char (point-max))))))
1252            result)))
1253       (nreverse result))))
1254
1255 (defun nnimap-last-response-string ()
1256   (save-excursion
1257     (forward-line 1)
1258     (let ((end (point)))
1259       (forward-line -1)
1260       (when (not (bobp))
1261         (forward-line -1)
1262         (while (and (not (bobp))
1263                     (eql (following-char) ?*))
1264           (forward-line -1))
1265         (unless (eql (following-char) ?*)
1266           (forward-line 1)))
1267       (buffer-substring (point) end))))
1268
1269 (defun nnimap-get-responses (sequences)
1270   (let (responses)
1271     (dolist (sequence sequences)
1272       (goto-char (point-min))
1273       (when (re-search-forward (format "^%d " sequence) nil t)
1274         (push (list sequence (nnimap-parse-response))
1275               responses)))
1276     responses))
1277
1278 (defvar nnimap-incoming-split-list nil)
1279
1280 (defun nnimap-fetch-inbox (articles)
1281   (erase-buffer)
1282   (nnimap-wait-for-response
1283    (nnimap-send-command
1284     "UID FETCH %s %s"
1285     (nnimap-article-ranges articles)
1286     (format "(UID %s%s)"
1287             (format
1288              (if (nnimap-ver4-p)
1289                  "BODY.PEEK[HEADER] BODY.PEEK"
1290                "RFC822.PEEK"))
1291             (if nnimap-split-download-body-default
1292                 "[]"
1293               "[1]")))
1294    t))
1295
1296 (defun nnimap-split-incoming-mail ()
1297   (with-current-buffer (nnimap-buffer)
1298     (let ((nnimap-incoming-split-list nil)
1299           (nnmail-split-methods nnimap-split-methods)
1300           (nnmail-inhibit-default-split-group t)
1301           (groups (nnimap-get-groups))
1302           new-articles)
1303       (erase-buffer)
1304       (nnimap-command "SELECT %S" nnimap-inbox)
1305       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1306       (when new-articles
1307         (nnimap-fetch-inbox new-articles)
1308         (nnimap-transform-split-mail)
1309         (nnheader-ms-strip-cr)
1310         (nnmail-cache-open)
1311         (nnmail-split-incoming (current-buffer)
1312                                #'nnimap-save-mail-spec
1313                                nil nil
1314                                #'nnimap-dummy-active-number
1315                                #'nnimap-save-mail-spec)
1316         (when nnimap-incoming-split-list
1317           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1318                 sequences junk-articles)
1319             ;; Create any groups that doesn't already exist on the
1320             ;; server first.
1321             (dolist (spec specs)
1322               (when (and (not (member (car spec) groups))
1323                          (not (eq (car spec) 'junk)))
1324                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1325             ;; Then copy over all the messages.
1326             (erase-buffer)
1327             (dolist (spec specs)
1328               (let ((group (car spec))
1329                     (ranges (cdr spec)))
1330                 (if (eq group 'junk)
1331                     (setq junk-articles ranges)
1332                   (push (list (nnimap-send-command
1333                                "UID COPY %s %S"
1334                                (nnimap-article-ranges ranges)
1335                                (utf7-encode group t))
1336                               ranges)
1337                         sequences))))
1338             ;; Wait for the last COPY response...
1339             (when sequences
1340               (nnimap-wait-for-response (caar sequences))
1341               ;; And then mark the successful copy actions as deleted,
1342               ;; and possibly expunge them.
1343               (nnimap-mark-and-expunge-incoming
1344                (nnimap-parse-copied-articles sequences)))
1345             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1346
1347 (defun nnimap-mark-and-expunge-incoming (range)
1348   (when range
1349     (setq range (nnimap-article-ranges range))
1350     (let ((sequence
1351            (nnimap-send-command
1352             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1353       (cond
1354        ;; If the server supports it, we now delete the message we have
1355        ;; just copied over.
1356        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1357         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1358        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1359        ;; user has configured it.
1360        (nnimap-expunge
1361         (setq sequence (nnimap-send-command "EXPUNGE"))))
1362       (nnimap-wait-for-response sequence))))
1363
1364 (defun nnimap-parse-copied-articles (sequences)
1365   (let (sequence copied range)
1366     (goto-char (point-min))
1367     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1368       (setq sequence (string-to-number (match-string 1)))
1369       (when (setq range (cadr (assq sequence sequences)))
1370         (push (gnus-uncompress-range range) copied)))
1371     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1372
1373 (defun nnimap-new-articles (flags)
1374   (let (new)
1375     (dolist (elem flags)
1376       (when (or (null (cdr elem))
1377                 (and (not (memq '%Deleted (cdr elem)))
1378                      (not (memq '%Seen (cdr elem)))))
1379         (push (car elem) new)))
1380     (gnus-compress-sequence (nreverse new))))
1381
1382 (defun nnimap-make-split-specs (list)
1383   (let ((specs nil)
1384         entry)
1385     (dolist (elem list)
1386       (destructuring-bind (article spec) elem
1387         (dolist (group (delete nil (mapcar #'car spec)))
1388           (unless (setq entry (assoc group specs))
1389             (push (setq entry (list group)) specs))
1390           (setcdr entry (cons article (cdr entry))))))
1391     (dolist (entry specs)
1392       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1393     specs))
1394
1395 (defun nnimap-transform-split-mail ()
1396   (goto-char (point-min))
1397   (let (article bytes)
1398     (block nil
1399       (while (not (eobp))
1400         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1401           (delete-region (point) (progn (forward-line 1) (point)))
1402           (when (eobp)
1403             (return)))
1404         (setq article (match-string 1)
1405               bytes (nnimap-get-length))
1406         (delete-region (line-beginning-position) (line-end-position))
1407         ;; Insert MMDF separator, and a way to remember what this
1408         ;; article UID is.
1409         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1410         (forward-char (1+ bytes))
1411         (setq bytes (nnimap-get-length))
1412         (delete-region (line-beginning-position) (line-end-position))
1413         (forward-char (1+ bytes))
1414         (delete-region (line-beginning-position) (line-end-position))))))
1415
1416 (defun nnimap-dummy-active-number (group &optional server)
1417   1)
1418
1419 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1420   (let (article)
1421     (goto-char (point-min))
1422     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1423         (error "Invalid nnimap mail")
1424       (setq article (string-to-number (match-string 1))))
1425     (push (list article
1426                 (if (eq group-art 'junk)
1427                     (list (cons 'junk 1))
1428                   group-art))
1429           nnimap-incoming-split-list)))
1430
1431 (provide 'nnimap)
1432
1433 ;;; nnimap.el ends here