Fix typo in last checkin.
[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           (gnus-set-active
971            group
972            (cons (car (gnus-active group))
973                  (or high (1- uidnext)))))
974         (when (and (not high)
975                    uidnext)
976           (setq high (1- uidnext)))
977         ;; Then update the list of read articles.
978         (let* ((unread
979                 (gnus-compress-sequence
980                  (gnus-set-difference
981                   (gnus-set-difference
982                    existing
983                    (cdr (assoc '%Seen flags)))
984                   (cdr (assoc '%Flagged flags)))))
985                (read (gnus-range-difference
986                       (cons start-article high) unread)))
987           (when (> start-article 1)
988             (setq read
989                   (gnus-range-nconcat
990                    (if (> start-article 1)
991                        (gnus-sorted-range-intersection
992                         (cons 1 (1- start-article))
993                         (gnus-info-read info))
994                      (gnus-info-read info))
995                    read)))
996           (gnus-info-set-read info read)
997           ;; Update the marks.
998           (setq marks (gnus-info-marks info))
999           ;; Note the active level for the next run-through.
1000           (let ((active (assq 'active marks)))
1001             (if active
1002                 (setcdr active (gnus-active group))
1003               (push (cons 'active (gnus-active group)) marks)))
1004           (dolist (type (cdr nnimap-mark-alist))
1005             (let ((old-marks (assoc (car type) marks))
1006                   (new-marks
1007                    (gnus-compress-sequence
1008                     (cdr (or (assoc (caddr type) flags)     ; %Flagged
1009                              (assoc (intern (cadr type) obarray) flags)
1010                              (assoc (cadr type) flags)))))) ; "\Flagged"
1011               (setq marks (delq old-marks marks))
1012               (pop old-marks)
1013               (when (and old-marks
1014                          (> start-article 1))
1015                 (setq old-marks (gnus-range-difference
1016                                  old-marks
1017                                  (cons start-article high)))
1018                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1019               (when new-marks
1020                 (push (cons (car type) new-marks) marks)))
1021             (gnus-info-set-marks info marks t)
1022             (nnimap-store-info info (gnus-active group))))))))
1023
1024 (defun nnimap-store-info (info active)
1025   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1026          (entry (assoc group nnimap-current-infos)))
1027     (if entry
1028         (setcdr entry (list info active))
1029       (push (list group info active) nnimap-current-infos))))
1030
1031 (defun nnimap-flags-to-marks (groups)
1032   (let (data group totalp uidnext articles start-article mark permanent-flags)
1033     (dolist (elem groups)
1034       (setq group (car elem)
1035             uidnext (nth 1 elem)
1036             start-article (nth 2 elem)
1037             permanent-flags (nth 3 elem)
1038             articles (nthcdr 4 elem))
1039       (let ((high (caar articles))
1040             marks low existing)
1041         (dolist (article articles)
1042           (setq low (car article))
1043           (push (car article) existing)
1044           (dolist (flag (cdr article))
1045             (setq mark (assoc flag marks))
1046             (if (not mark)
1047                 (push (list flag (car article)) marks)
1048               (setcdr mark (cons (car article) (cdr mark))))))
1049         (push (list group existing marks high low uidnext start-article
1050                     permanent-flags)
1051               data)))
1052     data))
1053
1054 (defun nnimap-parse-flags (sequences)
1055   (goto-char (point-min))
1056   ;; Change \Delete etc to %Delete, so that the reader can read it.
1057   (subst-char-in-region (point-min) (point-max)
1058                         ?\\ ?% t)
1059   (let (start end articles groups uidnext elems permanent-flags)
1060     (dolist (elem sequences)
1061       (destructuring-bind (group-sequence flag-sequence totalp group) elem
1062         (setq start (point))
1063         ;; The EXAMINE was successful.
1064         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
1065                    (progn
1066                      (forward-line 1)
1067                      (setq end (point))
1068                      (goto-char start)
1069                      (setq permanent-flags
1070                            (and (search-forward "PERMANENTFLAGS "
1071                                                  (or end (point-min)) t)
1072                                 (read (current-buffer))))
1073                      (goto-char start)
1074                      (setq uidnext
1075                            (and (search-forward "UIDNEXT "
1076                                                  (or end (point-min)) t)
1077                                 (read (current-buffer))))
1078                      (goto-char end)
1079                      (forward-line -1))
1080                    ;; The UID FETCH FLAGS was successful.
1081                    (search-forward (format "\n%d OK " flag-sequence) nil t))
1082           (setq start (point))
1083           (goto-char end)
1084           (while (search-forward " FETCH " start t)
1085             (setq elems (read (current-buffer)))
1086             (push (cons (cadr (memq 'UID elems))
1087                         (cadr (memq 'FLAGS elems)))
1088                   articles))
1089           (push (nconc (list group uidnext totalp permanent-flags) articles)
1090                 groups)
1091           (setq articles nil))))
1092     groups))
1093
1094 (defun nnimap-find-process-buffer (buffer)
1095   (cadr (assoc buffer nnimap-connection-alist)))
1096
1097 (deffoo nnimap-request-post (&optional server)
1098   (setq nnimap-status-string "Read-only server")
1099   nil)
1100
1101 (defun nnimap-possibly-change-group (group server)
1102   (let ((open-result t))
1103     (when (and server
1104                (not (nnimap-server-opened server)))
1105       (setq open-result (nnimap-open-server server)))
1106     (cond
1107      ((not open-result)
1108       nil)
1109      ((not group)
1110       t)
1111      (t
1112       (with-current-buffer (nnimap-buffer)
1113         (if (equal group (nnimap-group nnimap-object))
1114             t
1115           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1116             (when (car result)
1117               (setf (nnimap-group nnimap-object) group
1118                     (nnimap-select-result nnimap-object) result)
1119               result))))))))
1120
1121 (defun nnimap-find-connection (buffer)
1122   "Find the connection delivering to BUFFER."
1123   (let ((entry (assoc buffer nnimap-connection-alist)))
1124     (when entry
1125       (if (and (buffer-name (cadr entry))
1126                (get-buffer-process (cadr entry))
1127                (memq (process-status (get-buffer-process (cadr entry)))
1128                      '(open run)))
1129           (get-buffer-process (cadr entry))
1130         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1131         nil))))
1132
1133 (defvar nnimap-sequence 0)
1134
1135 (defun nnimap-send-command (&rest args)
1136   (process-send-string
1137    (get-buffer-process (current-buffer))
1138    (nnimap-log-command
1139     (format "%d %s%s\n"
1140             (incf nnimap-sequence)
1141             (apply #'format args)
1142             (if (nnimap-newlinep nnimap-object)
1143                 ""
1144               "\r"))))
1145   nnimap-sequence)
1146
1147 (defun nnimap-log-command (command)
1148   (with-current-buffer (get-buffer-create "*imap log*")
1149     (goto-char (point-max))
1150     (insert (format-time-string "%H:%M:%S") " " command))
1151   command)
1152
1153 (defun nnimap-command (&rest args)
1154   (erase-buffer)
1155   (setf (nnimap-last-command-time nnimap-object) (current-time))
1156   (let* ((sequence (apply #'nnimap-send-command args))
1157          (response (nnimap-get-response sequence)))
1158     (if (equal (caar response) "OK")
1159         (cons t response)
1160       (nnheader-report 'nnimap "%s"
1161                        (mapconcat (lambda (a)
1162                                     (format "%s" a))
1163                                   (car response) " "))
1164       nil)))
1165
1166 (defun nnimap-get-response (sequence)
1167   (nnimap-wait-for-response sequence)
1168   (nnimap-parse-response))
1169
1170 (defun nnimap-wait-for-connection ()
1171   (let ((process (get-buffer-process (current-buffer))))
1172     (goto-char (point-min))
1173     (while (and (memq (process-status process)
1174                       '(open run))
1175                 (not (re-search-forward "^\\* .*\n" nil t)))
1176       (nnheader-accept-process-output process)
1177       (goto-char (point-min)))
1178     (forward-line -1)
1179     (and (looking-at "\\* \\([A-Z0-9]+\\)")
1180          (match-string 1))))
1181
1182 (defun nnimap-wait-for-response (sequence &optional messagep)
1183   (let ((process (get-buffer-process (current-buffer)))
1184         openp)
1185     (goto-char (point-max))
1186     (while (and (setq openp (memq (process-status process)
1187                                   '(open run)))
1188                 (not (re-search-backward
1189                       (format "^%d .*\n" sequence)
1190                       (if nnimap-streaming
1191                           (max (point-min) (- (point) 500))
1192                         (point-min))
1193                       t)))
1194       (when messagep
1195         (message "Read %dKB" (/ (buffer-size) 1000)))
1196       (nnheader-accept-process-output process)
1197       (goto-char (point-max)))
1198     openp))
1199
1200 (defun nnimap-parse-response ()
1201   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1202         result)
1203     (dolist (line lines)
1204       (push (cdr (nnimap-parse-line line)) result))
1205     ;; Return the OK/error code first, and then all the "continuation
1206     ;; lines" afterwards.
1207     (cons (pop result)
1208           (nreverse result))))
1209
1210 ;; Parse an IMAP response line lightly.  They look like
1211 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1212 ;; the lines into a list of strings and lists of string.
1213 (defun nnimap-parse-line (line)
1214   (let (char result)
1215     (with-temp-buffer
1216       (insert line)
1217       (goto-char (point-min))
1218       (while (not (eobp))
1219         (if (eql (setq char (following-char)) ? )
1220             (forward-char 1)
1221           (push
1222            (cond
1223             ((eql char ?\[)
1224              (split-string (buffer-substring
1225                             (1+ (point))
1226                             (1- (search-forward "]" (line-end-position) 'move)))))
1227             ((eql char ?\()
1228              (split-string (buffer-substring
1229                             (1+ (point))
1230                             (1- (search-forward ")" (line-end-position) 'move)))))
1231             ((eql char ?\")
1232              (forward-char 1)
1233              (buffer-substring
1234               (point)
1235               (1- (or (search-forward "\"" (line-end-position) 'move)
1236                       (point)))))
1237             (t
1238              (buffer-substring (point) (if (search-forward " " nil t)
1239                                            (1- (point))
1240                                          (goto-char (point-max))))))
1241            result)))
1242       (nreverse result))))
1243
1244 (defun nnimap-last-response-string ()
1245   (save-excursion
1246     (forward-line 1)
1247     (let ((end (point)))
1248       (forward-line -1)
1249       (when (not (bobp))
1250         (forward-line -1)
1251         (while (and (not (bobp))
1252                     (eql (following-char) ?*))
1253           (forward-line -1))
1254         (unless (eql (following-char) ?*)
1255           (forward-line 1)))
1256       (buffer-substring (point) end))))
1257
1258 (defun nnimap-get-responses (sequences)
1259   (let (responses)
1260     (dolist (sequence sequences)
1261       (goto-char (point-min))
1262       (when (re-search-forward (format "^%d " sequence) nil t)
1263         (push (list sequence (nnimap-parse-response))
1264               responses)))
1265     responses))
1266
1267 (defvar nnimap-incoming-split-list nil)
1268
1269 (defun nnimap-fetch-inbox (articles)
1270   (erase-buffer)
1271   (nnimap-wait-for-response
1272    (nnimap-send-command
1273     "UID FETCH %s %s"
1274     (nnimap-article-ranges articles)
1275     (format "(UID %s%s)"
1276             (format
1277              (if (nnimap-ver4-p)
1278                  "BODY.PEEK[HEADER] BODY.PEEK"
1279                "RFC822.PEEK"))
1280             (if nnimap-split-download-body-default
1281                 "[]"
1282               "[1]")))
1283    t))
1284
1285 (defun nnimap-split-incoming-mail ()
1286   (with-current-buffer (nnimap-buffer)
1287     (let ((nnimap-incoming-split-list nil)
1288           (nnmail-split-methods nnimap-split-methods)
1289           (nnmail-inhibit-default-split-group t)
1290           (groups (nnimap-get-groups))
1291           new-articles)
1292       (erase-buffer)
1293       (nnimap-command "SELECT %S" nnimap-inbox)
1294       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1295       (when new-articles
1296         (nnimap-fetch-inbox new-articles)
1297         (nnimap-transform-split-mail)
1298         (nnheader-ms-strip-cr)
1299         (nnmail-cache-open)
1300         (nnmail-split-incoming (current-buffer)
1301                                #'nnimap-save-mail-spec
1302                                nil nil
1303                                #'nnimap-dummy-active-number
1304                                #'nnimap-save-mail-spec)
1305         (when nnimap-incoming-split-list
1306           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1307                 sequences junk-articles)
1308             ;; Create any groups that doesn't already exist on the
1309             ;; server first.
1310             (dolist (spec specs)
1311               (when (and (not (member (car spec) groups))
1312                          (not (eq (car spec) 'junk)))
1313                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1314             ;; Then copy over all the messages.
1315             (erase-buffer)
1316             (dolist (spec specs)
1317               (let ((group (car spec))
1318                     (ranges (cdr spec)))
1319                 (if (eq group 'junk)
1320                     (setq junk-articles ranges)
1321                   (push (list (nnimap-send-command
1322                                "UID COPY %s %S"
1323                                (nnimap-article-ranges ranges)
1324                                (utf7-encode group t))
1325                               ranges)
1326                         sequences))))
1327             ;; Wait for the last COPY response...
1328             (when sequences
1329               (nnimap-wait-for-response (caar sequences))
1330               ;; And then mark the successful copy actions as deleted,
1331               ;; and possibly expunge them.
1332               (nnimap-mark-and-expunge-incoming
1333                (nnimap-parse-copied-articles sequences)))
1334             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1335
1336 (defun nnimap-mark-and-expunge-incoming (range)
1337   (when range
1338     (setq range (nnimap-article-ranges range))
1339     (let ((sequence
1340            (nnimap-send-command
1341             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1342       (cond
1343        ;; If the server supports it, we now delete the message we have
1344        ;; just copied over.
1345        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1346         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1347        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1348        ;; user has configured it.
1349        (nnimap-expunge
1350         (setq sequence (nnimap-send-command "EXPUNGE"))))
1351       (nnimap-wait-for-response sequence))))
1352
1353 (defun nnimap-parse-copied-articles (sequences)
1354   (let (sequence copied range)
1355     (goto-char (point-min))
1356     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1357       (setq sequence (string-to-number (match-string 1)))
1358       (when (setq range (cadr (assq sequence sequences)))
1359         (push (gnus-uncompress-range range) copied)))
1360     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1361
1362 (defun nnimap-new-articles (flags)
1363   (let (new)
1364     (dolist (elem flags)
1365       (when (or (null (cdr elem))
1366                 (and (not (memq '%Deleted (cdr elem)))
1367                      (not (memq '%Seen (cdr elem)))))
1368         (push (car elem) new)))
1369     (gnus-compress-sequence (nreverse new))))
1370
1371 (defun nnimap-make-split-specs (list)
1372   (let ((specs nil)
1373         entry)
1374     (dolist (elem list)
1375       (destructuring-bind (article spec) elem
1376         (dolist (group (delete nil (mapcar #'car spec)))
1377           (unless (setq entry (assoc group specs))
1378             (push (setq entry (list group)) specs))
1379           (setcdr entry (cons article (cdr entry))))))
1380     (dolist (entry specs)
1381       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1382     specs))
1383
1384 (defun nnimap-transform-split-mail ()
1385   (goto-char (point-min))
1386   (let (article bytes)
1387     (block nil
1388       (while (not (eobp))
1389         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1390           (delete-region (point) (progn (forward-line 1) (point)))
1391           (when (eobp)
1392             (return)))
1393         (setq article (match-string 1)
1394               bytes (nnimap-get-length))
1395         (delete-region (line-beginning-position) (line-end-position))
1396         ;; Insert MMDF separator, and a way to remember what this
1397         ;; article UID is.
1398         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1399         (forward-char (1+ bytes))
1400         (setq bytes (nnimap-get-length))
1401         (delete-region (line-beginning-position) (line-end-position))
1402         (forward-char (1+ bytes))
1403         (delete-region (line-beginning-position) (line-end-position))))))
1404
1405 (defun nnimap-dummy-active-number (group &optional server)
1406   1)
1407
1408 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1409   (let (article)
1410     (goto-char (point-min))
1411     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1412         (error "Invalid nnimap mail")
1413       (setq article (string-to-number (match-string 1))))
1414     (push (list article
1415                 (if (eq group-art 'junk)
1416                     (list (cons 'junk 1))
1417                   group-art))
1418           nnimap-incoming-split-list)))
1419
1420 (provide 'nnimap)
1421
1422 ;;; nnimap.el ends here