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