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