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