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