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