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