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