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