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