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