Merge remote-tracking branch 'origin/no-gnus'
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010-2012 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 ;; For Emacs <22.2 and XEmacs.
30 (eval-and-compile
31   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
32
33 (eval-and-compile
34   (require 'nnheader)
35   ;; In Emacs 24, `open-protocol-stream' is an autoloaded alias for
36   ;; `make-network-stream'.
37   (unless (fboundp 'open-protocol-stream)
38     (require 'proto-stream)))
39
40 (eval-when-compile
41   (require 'cl))
42
43 (require 'nnheader)
44 (require 'gnus-util)
45 (require 'gnus)
46 (require 'nnoo)
47 (require 'netrc)
48 (require 'utf7)
49 (require 'tls)
50 (require 'parse-time)
51 (require 'nnmail)
52
53 (autoload 'auth-source-forget+ "auth-source")
54 (autoload 'auth-source-search "auth-source")
55
56 (nnoo-declare nnimap)
57
58 (defvoo nnimap-address nil
59   "The address of the IMAP server.")
60
61 (defvoo nnimap-user nil
62   "Username to use for authentication to the IMAP server.")
63
64 (defvoo nnimap-server-port nil
65   "The IMAP port used.
66 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
67 it will default to `imap'.")
68
69 (defvoo nnimap-stream 'undecided
70   "How nnimap talks to the IMAP server.
71 The value should be either `undecided', `ssl' or `tls',
72 `network', `starttls', `plain', or `shell'.
73
74 If the value is `undecided', nnimap tries `ssl' first, then falls
75 back on `network'.")
76
77 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
78                                  (if (listp imap-shell-program)
79                                      (car imap-shell-program)
80                                    imap-shell-program)
81                                "ssh %s imapd"))
82
83 (defvoo nnimap-inbox nil
84   "The mail box where incoming mail arrives and should be split out of.
85 For example, \"INBOX\".")
86
87 (defvoo nnimap-split-methods nil
88   "How mail is split.
89 Uses the same syntax as `nnmail-split-methods'.")
90
91 (defvoo nnimap-split-fancy nil
92   "Uses the same syntax as `nnmail-split-fancy'.")
93
94 (defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
95   "Articles with the flags in the list will not be considered when splitting.")
96
97 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
98                         "Emacs 24.1")
99
100 (defvoo nnimap-authenticator nil
101   "How nnimap authenticate itself to the server.
102 Possible choices are nil (use default methods) or `anonymous'.")
103
104 (defvoo nnimap-expunge t
105   "If non-nil, expunge articles after deleting them.
106 This is always done if the server supports UID EXPUNGE, but it's
107 not done by default on servers that doesn't support that command.")
108
109 (defvoo nnimap-streaming t
110   "If non-nil, try to use streaming commands with IMAP servers.
111 Switching this off will make nnimap slower, but it helps with
112 some servers.")
113
114 (defvoo nnimap-connection-alist nil)
115
116 (defvoo nnimap-current-infos nil)
117
118 (defvoo nnimap-fetch-partial-articles nil
119   "If non-nil, Gnus will fetch partial articles.
120 If t, nnimap will fetch only the first part.  If a string, it
121 will fetch all parts that have types that match that string.  A
122 likely value would be \"text/\" to automatically fetch all
123 textual parts.")
124
125 (defvar nnimap-process nil)
126
127 (defvar nnimap-status-string "")
128
129 (defvar nnimap-split-download-body-default nil
130   "Internal variable with default value for `nnimap-split-download-body'.")
131
132 (defvar nnimap-keepalive-timer nil)
133 (defvar nnimap-process-buffers nil)
134
135 (defstruct nnimap
136   group process commands capabilities select-result newlinep server
137   last-command-time greeting examined stream-type initial-resync)
138
139 (defvar nnimap-object nil)
140
141 (defvar nnimap-mark-alist
142   '((read "\\Seen" %Seen)
143     (tick "\\Flagged" %Flagged)
144     (reply "\\Answered" %Answered)
145     (expire "gnus-expire")
146     (dormant "gnus-dormant")
147     (score "gnus-score")
148     (save "gnus-save")
149     (download "gnus-download")
150     (forward "gnus-forward")))
151
152 (defvar nnimap-quirks
153   '(("QRESYNC" "Zimbra" "QRESYNC ")))
154
155 (defvar nnimap-inhibit-logging nil)
156
157 (defun nnimap-buffer ()
158   (nnimap-find-process-buffer nntp-server-buffer))
159
160 (defun nnimap-header-parameters ()
161   (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
162           (format
163            (if (nnimap-ver4-p)
164                "BODY.PEEK[HEADER.FIELDS %s]"
165              "RFC822.HEADER.LINES %s")
166            (append '(Subject From Date Message-Id
167                              References In-Reply-To Xref)
168                    nnmail-extra-headers))))
169
170 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
171   (when group
172     (setq group (nnimap-decode-gnus-group group)))
173   (with-current-buffer nntp-server-buffer
174     (erase-buffer)
175     (when (nnimap-possibly-change-group group server)
176       (with-current-buffer (nnimap-buffer)
177         (erase-buffer)
178         (nnimap-wait-for-response
179          (nnimap-send-command
180           "UID FETCH %s %s"
181           (nnimap-article-ranges (gnus-compress-sequence articles))
182           (nnimap-header-parameters))
183          t)
184         (nnimap-transform-headers)
185         (nnheader-remove-cr-followed-by-lf))
186       (insert-buffer-substring
187        (nnimap-find-process-buffer (current-buffer))))
188     'headers))
189
190 (defun nnimap-transform-headers ()
191   (goto-char (point-min))
192   (let (article bytes lines size string)
193     (block nil
194       (while (not (eobp))
195         (while (not (looking-at "\\* [0-9]+ FETCH.+?UID \\([0-9]+\\)"))
196           (delete-region (point) (progn (forward-line 1) (point)))
197           (when (eobp)
198             (return)))
199         (setq article (match-string 1))
200         ;; Unfold quoted {number} strings.
201         (while (re-search-forward "[^]][ (]{\\([0-9]+\\)}\r?\n"
202                                   (1+ (line-end-position)) t)
203           (setq size (string-to-number (match-string 1)))
204           (delete-region (+ (match-beginning 0) 2) (point))
205           (setq string (buffer-substring (point) (+ (point) size)))
206           (delete-region (point) (+ (point) size))
207           (insert (format "%S" string)))
208         (setq bytes (nnimap-get-length)
209               lines nil)
210         (beginning-of-line)
211         (setq size
212               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
213                                       (line-end-position)
214                                       t)
215                    (match-string 1)))
216         (beginning-of-line)
217         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
218           (let ((structure (ignore-errors
219                              (read (current-buffer)))))
220             (while (and (consp structure)
221                         (not (atom (car structure))))
222               (setq structure (car structure)))
223             (setq lines (if (and
224                              (stringp (car structure))
225                              (equal (upcase (nth 0 structure)) "MESSAGE")
226                              (equal (upcase (nth 1 structure)) "RFC822"))
227                             (nth 9 structure)
228                           (nth 7 structure)))))
229         (delete-region (line-beginning-position) (line-end-position))
230         (insert (format "211 %s Article retrieved." article))
231         (forward-line 1)
232         (when size
233           (insert (format "Chars: %s\n" size)))
234         (when lines
235           (insert (format "Lines: %s\n" lines)))
236         (unless (re-search-forward "^\r$" nil t)
237           (goto-char (point-max)))
238         (delete-region (line-beginning-position) (line-end-position))
239         (insert ".")
240         (forward-line 1)))))
241
242 (defun nnimap-unfold-quoted-lines ()
243   ;; Unfold quoted {number} strings.
244   (let (size string)
245     (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
246       (setq size (string-to-number (match-string 1)))
247       (delete-region (1+ (match-beginning 0)) (point))
248       (setq string (buffer-substring (point) (+ (point) size)))
249       (delete-region (point) (+ (point) size))
250       (insert (format "%S" string)))))
251
252 (defun nnimap-get-length ()
253   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
254        (string-to-number (match-string 1))))
255
256 (defun nnimap-article-ranges (ranges)
257   (let (result)
258     (cond
259      ((numberp ranges)
260       (number-to-string ranges))
261      ((numberp (cdr ranges))
262       (format "%d:%d" (car ranges) (cdr ranges)))
263      (t
264       (dolist (elem ranges)
265         (push
266          (if (consp elem)
267              (format "%d:%d" (car elem) (cdr elem))
268            (number-to-string elem))
269          result))
270       (mapconcat #'identity (nreverse result) ",")))))
271
272 (deffoo nnimap-open-server (server &optional defs)
273   (if (nnimap-server-opened server)
274       t
275     (unless (assq 'nnimap-address defs)
276       (setq defs (append defs (list (list 'nnimap-address server)))))
277     (nnoo-change-server 'nnimap server defs)
278     (or (nnimap-find-connection nntp-server-buffer)
279         (nnimap-open-connection nntp-server-buffer))))
280
281 (defun nnimap-make-process-buffer (buffer)
282   (with-current-buffer
283       (generate-new-buffer (format "*nnimap %s %s %s*"
284                                    nnimap-address nnimap-server-port
285                                    (gnus-buffer-exists-p buffer)))
286     (mm-disable-multibyte)
287     (buffer-disable-undo)
288     (gnus-add-buffer)
289     (set (make-local-variable 'after-change-functions) nil)
290     (set (make-local-variable 'nnimap-object)
291          (make-nnimap :server (nnoo-current-server 'nnimap)
292                       :initial-resync 0))
293     (push (list buffer (current-buffer)) nnimap-connection-alist)
294     (push (current-buffer) nnimap-process-buffers)
295     (current-buffer)))
296
297 (defun nnimap-credentials (address ports user)
298   (let* ((auth-source-creation-prompts
299           '((user  . "IMAP user at %h: ")
300             (secret . "IMAP password for %u@%h: ")))
301          (found (nth 0 (auth-source-search :max 1
302                                            :host address
303                                            :port ports
304                                            :user user
305                                            :require '(:user :secret)
306                                            :create t))))
307     (if found
308         (list (plist-get found :user)
309               (let ((secret (plist-get found :secret)))
310                 (if (functionp secret)
311                     (funcall secret)
312                   secret))
313               (plist-get found :save-function))
314       nil)))
315
316 (defun nnimap-keepalive ()
317   (let ((now (current-time)))
318     (dolist (buffer nnimap-process-buffers)
319       (when (buffer-name buffer)
320         (with-current-buffer buffer
321           (when (and nnimap-object
322                      (nnimap-last-command-time nnimap-object)
323                      (> (gnus-float-time
324                          (time-subtract
325                           now
326                           (nnimap-last-command-time nnimap-object)))
327                         ;; More than five minutes since the last command.
328                         (* 5 60)))
329             (nnimap-send-command "NOOP")))))))
330
331 (defun nnimap-open-connection (buffer)
332   ;; Be backwards-compatible -- the earlier value of nnimap-stream was
333   ;; `ssl' when nnimap-server-port was nil.  Sort of.
334   (when (and nnimap-server-port
335              (eq nnimap-stream 'undecided))
336     (setq nnimap-stream 'ssl))
337   (let ((stream
338          (if (eq nnimap-stream 'undecided)
339              (loop for type in '(ssl network)
340                    for stream = (let ((nnimap-stream type))
341                                   (nnimap-open-connection-1 buffer))
342                    while (eq stream 'no-connect)
343                    finally (return stream))
344            (nnimap-open-connection-1 buffer))))
345     (if (eq stream 'no-connect)
346         nil
347       stream)))
348
349 (defun nnimap-map-port (port)
350   (if (equal port "imaps")
351       "993"
352     port))
353
354 (defun nnimap-open-connection-1 (buffer)
355   (unless nnimap-keepalive-timer
356     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
357                                               'nnimap-keepalive)))
358   (with-current-buffer (nnimap-make-process-buffer buffer)
359     (let* ((coding-system-for-read 'binary)
360            (coding-system-for-write 'binary)
361            (ports
362             (cond
363              ((memq nnimap-stream '(network plain starttls))
364               (nnheader-message 7 "Opening connection to %s..."
365                                 nnimap-address)
366               '("imap" "143"))
367              ((eq nnimap-stream 'shell)
368               (nnheader-message 7 "Opening connection to %s via shell..."
369                                 nnimap-address)
370               '("imap"))
371              ((memq nnimap-stream '(ssl tls))
372               (nnheader-message 7 "Opening connection to %s via tls..."
373                                 nnimap-address)
374               '("imaps" "imap" "993" "143"))
375              (t
376               (error "Unknown stream type: %s" nnimap-stream))))
377            login-result credentials)
378       (when nnimap-server-port
379         (push nnimap-server-port ports))
380       (let* ((stream-list
381               (open-protocol-stream
382                "*nnimap*" (current-buffer) nnimap-address
383                (nnimap-map-port (car ports))
384                :type nnimap-stream
385                :return-list t
386                :shell-command nnimap-shell-program
387                :capability-command "1 CAPABILITY\r\n"
388                :end-of-command "\r\n"
389                :success " OK "
390                :starttls-function
391                (lambda (capabilities)
392                  (when (gnus-string-match-p "STARTTLS" capabilities)
393                    "1 STARTTLS\r\n"))))
394              (stream (car stream-list))
395              (props (cdr stream-list))
396              (greeting (plist-get props :greeting))
397              (capabilities (plist-get props :capabilities))
398              (stream-type (plist-get props :type)))
399         (when (and stream (not (memq (process-status stream) '(open run))))
400           (setq stream nil))
401
402         (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
403                    (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
404                    (eq (process-type stream) 'network))
405           ;; Use TCP-keepalive so that connections that pass through a NAT
406           ;; router don't hang when left idle.
407           (set-network-process-option stream :keepalive t))
408
409         (setf (nnimap-process nnimap-object) stream)
410         (setf (nnimap-stream-type nnimap-object) stream-type)
411         (if (not stream)
412             (progn
413               (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
414                                nnimap-address (car ports) nnimap-stream)
415               'no-connect)
416           (gnus-set-process-query-on-exit-flag stream nil)
417           (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
418               (nnheader-report 'nnimap "%s" greeting)
419             ;; Store the greeting (for debugging purposes).
420             (setf (nnimap-greeting nnimap-object) greeting)
421             (setf (nnimap-capabilities nnimap-object)
422                   (mapcar #'upcase
423                           (split-string capabilities)))
424             (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
425               (if (not (setq credentials
426                              (if (eq nnimap-authenticator 'anonymous)
427                                  (list "anonymous"
428                                        (message-make-address))
429                                ;; Look for the credentials based on
430                                ;; the virtual server name and the address
431                                (nnimap-credentials
432                                 (gnus-delete-duplicates
433                                  (list
434                                   nnimap-address
435                                   (nnoo-current-server 'nnimap)))
436                                 ports
437                                 nnimap-user))))
438                   (setq nnimap-object nil)
439                 (let ((nnimap-inhibit-logging t))
440                   (setq login-result
441                         (nnimap-login (car credentials) (cadr credentials))))
442                 (if (car login-result)
443                     (progn
444                       ;; Save the credentials if a save function exists
445                       ;; (such a function will only be passed if a new
446                       ;; token was created).
447                       (when (functionp (nth 2 credentials))
448                         (funcall (nth 2 credentials)))
449                       ;; See if CAPABILITY is set as part of login
450                       ;; response.
451                       (dolist (response (cddr login-result))
452                         (when (string= "CAPABILITY" (upcase (car response)))
453                           (setf (nnimap-capabilities nnimap-object)
454                                 (mapcar #'upcase (cdr response))))))
455                   ;; If the login failed, then forget the credentials
456                   ;; that are now possibly cached.
457                   (dolist (host (list (nnoo-current-server 'nnimap)
458                                       nnimap-address))
459                     (dolist (port ports)
460                       (auth-source-forget+ :host host :port port)))
461                   (delete-process (nnimap-process nnimap-object))
462                   (setq nnimap-object nil))))
463             (when nnimap-object
464               (when (nnimap-capability "QRESYNC")
465                 (nnimap-command "ENABLE QRESYNC"))
466               (nnimap-process nnimap-object))))))))
467
468 (autoload 'rfc2104-hash "rfc2104")
469
470 (defun nnimap-login (user password)
471   (cond
472    ;; Prefer plain LOGIN if it's enabled (since it requires fewer
473    ;; round trips than CRAM-MD5, and it's less likely to be buggy),
474    ;; and we're using an encrypted connection.
475    ((and (not (nnimap-capability "LOGINDISABLED"))
476          (eq (nnimap-stream-type nnimap-object) 'tls))
477     (nnimap-command "LOGIN %S %S" user password))
478    ((nnimap-capability "AUTH=CRAM-MD5")
479     (erase-buffer)
480     (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
481           (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
482       (process-send-string
483        (get-buffer-process (current-buffer))
484        (concat
485         (base64-encode-string
486          (concat user " "
487                  (rfc2104-hash 'md5 64 16 password
488                                (base64-decode-string challenge))))
489         "\r\n"))
490       (nnimap-wait-for-response sequence)))
491    ((not (nnimap-capability "LOGINDISABLED"))
492     (nnimap-command "LOGIN %S %S" user password))
493    ((nnimap-capability "AUTH=PLAIN")
494     (nnimap-command
495      "AUTHENTICATE PLAIN %s"
496      (base64-encode-string
497       (format "\000%s\000%s"
498               (nnimap-quote-specials user)
499               (nnimap-quote-specials password)))))))
500
501 (defun nnimap-quote-specials (string)
502   (with-temp-buffer
503     (insert string)
504     (goto-char (point-min))
505     (while (re-search-forward "[\\\"]" nil t)
506       (forward-char -1)
507       (insert "\\")
508       (forward-char 1))
509     (buffer-string)))
510
511 (defun nnimap-find-parameter (parameter elems)
512   (let (result)
513     (dolist (elem elems)
514       (cond
515        ((equal (car elem) parameter)
516         (setq result (cdr elem)))
517        ((and (equal (car elem) "OK")
518              (consp (cadr elem))
519              (equal (caadr elem) parameter))
520         (setq result (cdr (cadr elem))))))
521     result))
522
523 (deffoo nnimap-close-server (&optional server)
524   (when (nnoo-change-server 'nnimap server nil)
525     (ignore-errors
526       (delete-process (get-buffer-process (nnimap-buffer))))
527     (nnoo-close-server 'nnimap server)
528     t))
529
530 (deffoo nnimap-request-close ()
531   t)
532
533 (deffoo nnimap-server-opened (&optional server)
534   (and (nnoo-current-server-p 'nnimap server)
535        nntp-server-buffer
536        (gnus-buffer-live-p nntp-server-buffer)
537        (nnimap-find-connection nntp-server-buffer)))
538
539 (deffoo nnimap-status-message (&optional server)
540   nnimap-status-string)
541
542 (deffoo nnimap-request-article (article &optional group server to-buffer)
543   (when group
544     (setq group (nnimap-decode-gnus-group group)))
545   (with-current-buffer nntp-server-buffer
546     (let ((result (nnimap-possibly-change-group group server))
547           parts structure)
548       (when (stringp article)
549         (setq article (nnimap-find-article-by-message-id group article)))
550       (when (and result
551                  article)
552         (erase-buffer)
553         (with-current-buffer (nnimap-buffer)
554           (erase-buffer)
555           (when nnimap-fetch-partial-articles
556             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
557             (goto-char (point-min))
558             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
559               (setq structure (ignore-errors
560                                 (let ((start (point)))
561                                   (forward-sexp 1)
562                                   (downcase-region start (point))
563                                   (goto-char start)
564                                   (read (current-buffer))))
565                     parts (nnimap-find-wanted-parts structure))))
566           (when (if parts
567                     (nnimap-get-partial-article article parts structure)
568                   (nnimap-get-whole-article article))
569             (let ((buffer (current-buffer)))
570               (with-current-buffer (or to-buffer nntp-server-buffer)
571                 (nnheader-insert-buffer-substring buffer)
572                 (nnheader-ms-strip-cr)))
573             (cons group article)))))))
574
575 (deffoo nnimap-request-head (article &optional group server to-buffer)
576   (when group
577     (setq group (nnimap-decode-gnus-group group)))
578   (when (nnimap-possibly-change-group group server)
579     (with-current-buffer (nnimap-buffer)
580       (when (stringp article)
581         (setq article (nnimap-find-article-by-message-id group article)))
582       (if (null article)
583           nil
584         (nnimap-get-whole-article
585          article (format "UID FETCH %%d %s"
586                          (nnimap-header-parameters)))
587         (let ((buffer (current-buffer)))
588           (with-current-buffer (or to-buffer nntp-server-buffer)
589             (erase-buffer)
590             (insert-buffer-substring buffer)
591             (nnheader-ms-strip-cr)
592             (cons group article)))))))
593
594 (defun nnimap-get-whole-article (article &optional command)
595   (let ((result
596          (nnimap-command
597           (or command
598               (if (nnimap-ver4-p)
599                   "UID FETCH %d BODY.PEEK[]"
600                 "UID FETCH %d RFC822.PEEK"))
601           article)))
602     ;; Check that we really got an article.
603     (goto-char (point-min))
604     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
605       (setq result nil))
606     (when result
607       ;; Remove any data that may have arrived before the FETCH data.
608       (beginning-of-line)
609       (unless (bobp)
610         (delete-region (point-min) (point)))
611       (let ((bytes (nnimap-get-length)))
612         (delete-region (line-beginning-position)
613                        (progn (forward-line 1) (point)))
614         (goto-char (+ (point) bytes))
615         (delete-region (point) (point-max)))
616       t)))
617
618 (defun nnimap-capability (capability)
619   (member capability (nnimap-capabilities nnimap-object)))
620
621 (defun nnimap-ver4-p ()
622   (nnimap-capability "IMAP4REV1"))
623
624 (defun nnimap-get-partial-article (article parts structure)
625   (let ((result
626          (nnimap-command
627           "UID FETCH %d (%s %s)"
628           article
629           (if (nnimap-ver4-p)
630               "BODY.PEEK[HEADER]"
631             "RFC822.HEADER")
632           (if (nnimap-ver4-p)
633               (mapconcat (lambda (part)
634                            (format "BODY.PEEK[%s]" part))
635                          parts " ")
636             (mapconcat (lambda (part)
637                          (format "RFC822.PEEK[%s]" part))
638                        parts " ")))))
639     (when result
640       (nnimap-convert-partial-article structure))))
641
642 (defun nnimap-convert-partial-article (structure)
643   ;; First just skip past the headers.
644   (goto-char (point-min))
645   (let ((bytes (nnimap-get-length))
646         id parts)
647     ;; Delete "FETCH" line.
648     (delete-region (line-beginning-position)
649                    (progn (forward-line 1) (point)))
650     (goto-char (+ (point) bytes))
651     ;; Collect all the body parts.
652     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
653       (setq id (match-string 1)
654             bytes (or (nnimap-get-length) 0))
655       (beginning-of-line)
656       (delete-region (point) (progn (forward-line 1) (point)))
657       (push (list id (buffer-substring (point) (+ (point) bytes)))
658             parts)
659       (delete-region (point) (+ (point) bytes)))
660     ;; Delete trailing junk.
661     (delete-region (point) (point-max))
662     ;; Now insert all the parts again where they fit in the structure.
663     (nnimap-insert-partial-structure structure parts)
664     t))
665
666 (defun nnimap-insert-partial-structure (structure parts &optional subp)
667   (let (type boundary)
668     (let ((bstruc structure))
669       (while (consp (car bstruc))
670         (pop bstruc))
671       (setq type (car bstruc))
672       (setq bstruc (car (cdr bstruc)))
673       (let ((has-boundary (member "boundary" bstruc)))
674         (when has-boundary
675           (setq boundary (cadr has-boundary)))))
676     (when subp
677       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
678                       (downcase type) boundary)))
679     (while (not (stringp (car structure)))
680       (insert "\n--" boundary "\n")
681       (if (consp (caar structure))
682           (nnimap-insert-partial-structure (pop structure) parts t)
683         (let ((bit (pop structure)))
684           (insert (format "Content-type: %s/%s"
685                           (downcase (nth 0 bit))
686                           (downcase (nth 1 bit))))
687           (if (member-ignore-case "CHARSET" (nth 2 bit))
688               (insert (format
689                        "; charset=%S\n"
690                        (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
691             (insert "\n"))
692           (insert (format "Content-transfer-encoding: %s\n"
693                           (nth 5 bit)))
694           (insert "\n")
695           (when (assoc (nth 9 bit) parts)
696             (insert (cadr (assoc (nth 9 bit) parts)))))))
697     (insert "\n--" boundary "--\n")))
698
699 (defun nnimap-find-wanted-parts (structure)
700   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
701
702 (defun nnimap-find-wanted-parts-1 (structure prefix)
703   (let ((num 1)
704         parts)
705     (while (consp (car structure))
706       (let ((sub (pop structure)))
707         (if (consp (car sub))
708             (push (nnimap-find-wanted-parts-1
709                    sub (if (string= prefix "")
710                            (number-to-string num)
711                          (format "%s.%s" prefix num)))
712                   parts)
713           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
714                 (id (if (string= prefix "")
715                         (number-to-string num)
716                       (format "%s.%s" prefix num))))
717             (setcar (nthcdr 9 sub) id)
718             (when (if (eq nnimap-fetch-partial-articles t)
719                       (equal id "1")
720                     (string-match nnimap-fetch-partial-articles type))
721               (push id parts))))
722         (incf num)))
723     (nreverse parts)))
724
725 (defun nnimap-decode-gnus-group (group)
726   (decode-coding-string group 'utf-8))
727
728 (deffoo nnimap-request-group (group &optional server dont-check info)
729   (setq group (nnimap-decode-gnus-group group))
730   (let ((result (nnimap-possibly-change-group
731                  ;; Don't SELECT the group if we're going to select it
732                  ;; later, anyway.
733                  (if (and (not dont-check)
734                           (assoc group nnimap-current-infos))
735                      nil
736                    group)
737                  server))
738         articles active marks high low)
739     (with-current-buffer nntp-server-buffer
740       (when result
741         (if (and dont-check
742                  (setq active (nth 2 (assoc group nnimap-current-infos))))
743             (insert (format "211 %d %d %d %S\n"
744                             (- (cdr active) (car active))
745                             (car active)
746                             (cdr active)
747                             group))
748           (with-current-buffer (nnimap-buffer)
749             (erase-buffer)
750             (let ((group-sequence
751                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
752                   (flag-sequence
753                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
754               (setf (nnimap-group nnimap-object) group)
755               (nnimap-wait-for-response flag-sequence)
756               (setq marks
757                     (nnimap-flags-to-marks
758                      (nnimap-parse-flags
759                       (list (list group-sequence flag-sequence
760                                   1 group "SELECT")))))
761               (when (and info
762                          marks)
763                 (nnimap-update-infos marks (list info))
764                 (nnimap-store-info info (gnus-active (gnus-info-group info))))
765               (goto-char (point-max))
766               (let ((uidnext (nth 5 (car marks))))
767                 (setq high (or (if uidnext
768                                    (1- uidnext)
769                                  (nth 3 (car marks)))
770                                0)
771                       low (or (nth 4 (car marks)) uidnext 1)))))
772           (erase-buffer)
773           (insert
774            (format
775             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
776         t))))
777
778 (deffoo nnimap-request-create-group (group &optional server args)
779   (setq group (nnimap-decode-gnus-group group))
780   (when (nnimap-possibly-change-group nil server)
781     (with-current-buffer (nnimap-buffer)
782       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
783
784 (deffoo nnimap-request-delete-group (group &optional force server)
785   (setq group (nnimap-decode-gnus-group group))
786   (when (nnimap-possibly-change-group nil server)
787     (with-current-buffer (nnimap-buffer)
788       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
789
790 (deffoo nnimap-request-rename-group (group new-name &optional server)
791   (setq group (nnimap-decode-gnus-group group))
792   (when (nnimap-possibly-change-group nil server)
793     (with-current-buffer (nnimap-buffer)
794       (nnimap-unselect-group)
795       (car (nnimap-command "RENAME %S %S"
796                            (utf7-encode group t) (utf7-encode new-name t))))))
797
798 (defun nnimap-unselect-group ()
799   ;; Make sure we don't have this group open read/write by asking
800   ;; to examine a mailbox that doesn't exist.  This seems to be
801   ;; the only way that allows us to reliably go back to unselected
802   ;; state on Courier.
803   (nnimap-command "EXAMINE DOES.NOT.EXIST"))
804
805 (deffoo nnimap-request-expunge-group (group &optional server)
806   (setq group (nnimap-decode-gnus-group group))
807   (when (nnimap-possibly-change-group group server)
808     (with-current-buffer (nnimap-buffer)
809       (car (nnimap-command "EXPUNGE")))))
810
811 (defun nnimap-get-flags (spec)
812   (let ((articles nil)
813         elems end)
814     (with-current-buffer (nnimap-buffer)
815       (erase-buffer)
816       (nnimap-wait-for-response (nnimap-send-command
817                                  "UID FETCH %s FLAGS" spec))
818       (setq end (point))
819       (subst-char-in-region (point-min) (point-max)
820                             ?\\ ?% t)
821       (goto-char (point-min))
822       (while (search-forward " FETCH " end t)
823         (setq elems (read (current-buffer)))
824         (push (cons (cadr (memq 'UID elems))
825                     (cadr (memq 'FLAGS elems)))
826               articles)))
827     (nreverse articles)))
828
829 (deffoo nnimap-close-group (group &optional server)
830   t)
831
832 (deffoo nnimap-request-move-article (article group server accept-form
833                                              &optional last internal-move-group)
834   (setq group (nnimap-decode-gnus-group group))
835   (with-temp-buffer
836     (mm-disable-multibyte)
837     (when (funcall (if internal-move-group
838                        'nnimap-request-head
839                      'nnimap-request-article)
840                    article group server (current-buffer))
841       ;; If the move is internal (on the same server), just do it the easy
842       ;; way.
843       (let ((message-id (message-field-value "message-id")))
844         (if internal-move-group
845             (let ((result
846                    (with-current-buffer (nnimap-buffer)
847                      (nnimap-command "UID COPY %d %S"
848                                      article
849                                      (utf7-encode internal-move-group t)))))
850               (when (car result)
851                 (nnimap-delete-article article)
852                 (cons internal-move-group
853                       (or (nnimap-find-uid-response "COPYUID" (cadr result))
854                           (nnimap-find-article-by-message-id
855                            internal-move-group message-id)))))
856           ;; Move the article to a different method.
857           (let ((result (eval accept-form)))
858             (when result
859               (nnimap-delete-article article)
860               result)))))))
861
862 (deffoo nnimap-request-expire-articles (articles group &optional server force)
863   (setq group (nnimap-decode-gnus-group group))
864   (cond
865    ((null articles)
866     nil)
867    ((not (nnimap-possibly-change-group group server))
868     articles)
869    ((and force
870          (eq nnmail-expiry-target 'delete))
871     (unless (nnimap-delete-article (gnus-compress-sequence articles))
872       (nnheader-message 7 "Article marked for deletion, but not expunged."))
873     nil)
874    (t
875     (let ((deletable-articles
876            (if (or force
877                    (eq nnmail-expiry-wait 'immediate))
878                articles
879              (gnus-sorted-intersection
880               articles
881               (nnimap-find-expired-articles group)))))
882       (if (null deletable-articles)
883           articles
884         (if (eq nnmail-expiry-target 'delete)
885             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
886           (setq deletable-articles
887                 (nnimap-process-expiry-targets
888                  deletable-articles group server)))
889         ;; Return the articles we didn't delete.
890         (gnus-sorted-complement articles deletable-articles))))))
891
892 (defun nnimap-process-expiry-targets (articles group server)
893   (let ((deleted-articles nil))
894     (cond
895      ;; shortcut further processing if we're going to delete the articles
896      ((eq nnmail-expiry-target 'delete)
897       (setq deleted-articles articles)
898       t)
899      ;; or just move them to another folder on the same IMAP server
900      ((and (not (functionp nnmail-expiry-target))
901            (gnus-server-equal (gnus-group-method nnmail-expiry-target)
902                               (gnus-server-to-method
903                                (format "nnimap:%s" server))))
904       (and (nnimap-possibly-change-group group server)
905            (with-current-buffer (nnimap-buffer)
906              (nnheader-message 7 "Expiring articles from %s: %s" group articles)
907              (nnimap-command
908               "UID COPY %s %S"
909               (nnimap-article-ranges (gnus-compress-sequence articles))
910               (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
911              (setq deleted-articles articles)))
912       t)
913      (t
914       (dolist (article articles)
915         (let ((target nnmail-expiry-target))
916           (with-temp-buffer
917             (mm-disable-multibyte)
918             (when (nnimap-request-article article group server (current-buffer))
919               (when (functionp target)
920                 (setq target (funcall target group)))
921               (if (and target
922                        (not (eq target 'delete)))
923                   (if (or (gnus-request-group target t)
924                           (gnus-request-create-group target))
925                       (progn
926                         (nnmail-expiry-target-group target group)
927                         (nnheader-message 7 "Expiring article %s:%d to %s"
928                                           group article target))
929                     (setq target nil))
930                 (nnheader-message 7 "Expiring article %s:%d" group article))
931               (when target
932                 (push article deleted-articles))))))))
933     ;; Change back to the current group again.
934     (nnimap-possibly-change-group group server)
935     (setq deleted-articles (nreverse deleted-articles))
936     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
937     deleted-articles))
938
939 (defun nnimap-find-expired-articles (group)
940   (let ((cutoff (nnmail-expired-article-p group nil nil)))
941     (with-current-buffer (nnimap-buffer)
942       (let ((result
943              (nnimap-command
944               "UID SEARCH SENTBEFORE %s"
945               (format-time-string
946                (format "%%d-%s-%%Y"
947                        (upcase
948                         (car (rassoc (nth 4 (decode-time cutoff))
949                                      parse-time-months))))
950                cutoff))))
951         (and (car result)
952              (delete 0 (mapcar #'string-to-number
953                                (cdr (assoc "SEARCH" (cdr result))))))))))
954
955
956 (defun nnimap-find-article-by-message-id (group message-id)
957   (with-current-buffer (nnimap-buffer)
958     (erase-buffer)
959     (unless (equal group (nnimap-group nnimap-object))
960       (setf (nnimap-group nnimap-object) nil)
961       (setf (nnimap-examined nnimap-object) group)
962       (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
963     (let ((sequence
964            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
965           article result)
966       (setq result (nnimap-wait-for-response sequence))
967       (when (and result
968                  (car (setq result (nnimap-parse-response))))
969         ;; Select the last instance of the message in the group.
970         (and (setq article
971                    (car (last (cdr (assoc "SEARCH" (cdr result))))))
972              (string-to-number article))))))
973
974 (defun nnimap-delete-article (articles)
975   (with-current-buffer (nnimap-buffer)
976     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
977                     (nnimap-article-ranges articles))
978     (cond
979      ((nnimap-capability "UIDPLUS")
980       (nnimap-command "UID EXPUNGE %s"
981                       (nnimap-article-ranges articles))
982       t)
983      (nnimap-expunge
984       (nnimap-command "EXPUNGE")
985       t)
986      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
987                                 "server doesn't support UIDPLUS, so we won't "
988                                 "delete this article now"))))))
989
990 (deffoo nnimap-request-scan (&optional group server)
991   (when group
992     (setq group (nnimap-decode-gnus-group group)))
993   (when (and (nnimap-possibly-change-group nil server)
994              nnimap-inbox
995              nnimap-split-methods)
996     (nnheader-message 7 "nnimap %s splitting mail..." server)
997     (nnimap-split-incoming-mail)
998     (nnheader-message 7 "nnimap %s splitting mail...done" server)))
999
1000 (defun nnimap-marks-to-flags (marks)
1001   (let (flags flag)
1002     (dolist (mark marks)
1003       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1004         (push flag flags)))
1005     flags))
1006
1007 (deffoo nnimap-request-update-group-status (group status &optional server)
1008   (setq group (nnimap-decode-gnus-group group))
1009   (when (nnimap-possibly-change-group nil server)
1010     (let ((command (assoc
1011                     status
1012                     '((subscribe "SUBSCRIBE")
1013                       (unsubscribe "UNSUBSCRIBE")))))
1014       (when command
1015         (with-current-buffer (nnimap-buffer)
1016           (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1017
1018 (deffoo nnimap-request-set-mark (group actions &optional server)
1019   (setq group (nnimap-decode-gnus-group group))
1020   (when (nnimap-possibly-change-group group server)
1021     (let (sequence)
1022       (with-current-buffer (nnimap-buffer)
1023         (erase-buffer)
1024         ;; Just send all the STORE commands without waiting for
1025         ;; response.  If they're successful, they're successful.
1026         (dolist (action actions)
1027           (destructuring-bind (range action marks) action
1028             (let ((flags (nnimap-marks-to-flags marks)))
1029               (when flags
1030                 (setq sequence (nnimap-send-command
1031                                 "UID STORE %s %sFLAGS.SILENT (%s)"
1032                                 (nnimap-article-ranges range)
1033                                 (cond
1034                                  ((eq action 'del) "-")
1035                                  ((eq action 'add) "+")
1036                                  ((eq action 'set) ""))
1037                                 (mapconcat #'identity flags " ")))))))
1038         ;; Wait for the last command to complete to avoid later
1039         ;; synchronization problems with the stream.
1040         (when sequence
1041           (nnimap-wait-for-response sequence))))))
1042
1043 (deffoo nnimap-request-accept-article (group &optional server last)
1044   (setq group (nnimap-decode-gnus-group group))
1045   (when (nnimap-possibly-change-group nil server)
1046     (nnmail-check-syntax)
1047     (let ((message-id (message-field-value "message-id"))
1048           sequence message)
1049       (nnimap-add-cr)
1050       (setq message (buffer-substring-no-properties (point-min) (point-max)))
1051       (with-current-buffer (nnimap-buffer)
1052         (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1053                                 message))
1054           ;; If we have this group open read-only, then unselect it
1055           ;; before appending to it.
1056           (when (equal (nnimap-examined nnimap-object) group)
1057             (nnimap-unselect-group))
1058           (erase-buffer)
1059           (setq sequence (nnimap-send-command
1060                           "APPEND %S {%d}" (utf7-encode group t)
1061                           (length message)))
1062           (unless nnimap-streaming
1063             (nnimap-wait-for-connection "^[+]"))
1064           (process-send-string (get-buffer-process (current-buffer)) message)
1065           (process-send-string (get-buffer-process (current-buffer))
1066                                (if (nnimap-newlinep nnimap-object)
1067                                    "\n"
1068                                  "\r\n"))
1069           (let ((result (nnimap-get-response sequence)))
1070             (if (not (nnimap-ok-p result))
1071                 (progn
1072                   (nnheader-report 'nnimap "%s" result)
1073                   nil)
1074               (cons group
1075                     (or (nnimap-find-uid-response "APPENDUID" (car result))
1076                         (nnimap-find-article-by-message-id
1077                          group message-id))))))))))
1078
1079 (defun nnimap-process-quirk (greeting-match type data)
1080   (when (and (nnimap-greeting nnimap-object)
1081              (string-match greeting-match (nnimap-greeting nnimap-object))
1082              (eq type 'append)
1083              (string-match "\000" data))
1084     (let ((choice (gnus-multiple-choice
1085                    "Message contains NUL characters.  Delete, continue, abort? "
1086                    '((?d "Delete NUL characters")
1087                      (?c "Try to APPEND the message as is")
1088                      (?a "Abort")))))
1089       (cond
1090        ((eq choice ?a)
1091         (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1092        ((eq choice ?c)
1093         data)
1094        (t
1095         (with-temp-buffer
1096           (insert data)
1097           (goto-char (point-min))
1098           (while (search-forward "\000" nil t)
1099             (replace-match "" t t))
1100           (buffer-string)))))))
1101
1102 (defun nnimap-ok-p (value)
1103   (and (consp value)
1104        (consp (car value))
1105        (equal (caar value) "OK")))
1106
1107 (defun nnimap-find-uid-response (name list)
1108   (let ((result (car (last (nnimap-find-response-element name list)))))
1109     (and result
1110          (string-to-number result))))
1111
1112 (defun nnimap-find-response-element (name list)
1113   (let (result)
1114     (dolist (elem list)
1115       (when (and (consp elem)
1116                  (equal name (car elem)))
1117         (setq result elem)))
1118     result))
1119
1120 (deffoo nnimap-request-replace-article (article group buffer)
1121   (setq group (nnimap-decode-gnus-group group))
1122   (let (group-art)
1123     (when (and (nnimap-possibly-change-group group nil)
1124                ;; Put the article into the group.
1125                (with-current-buffer buffer
1126                  (setq group-art
1127                        (nnimap-request-accept-article group nil t))))
1128       (nnimap-delete-article (list article))
1129       ;; Return the new article number.
1130       (cdr group-art))))
1131
1132 (defun nnimap-add-cr ()
1133   (goto-char (point-min))
1134   (while (re-search-forward "\r?\n" nil t)
1135     (replace-match "\r\n" t t)))
1136
1137 (defun nnimap-get-groups ()
1138   (erase-buffer)
1139   (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1140         groups)
1141     (nnimap-wait-for-response sequence)
1142     (subst-char-in-region (point-min) (point-max)
1143                           ?\\ ?% t)
1144     (goto-char (point-min))
1145     (nnimap-unfold-quoted-lines)
1146     (goto-char (point-min))
1147     (while (search-forward "* LIST " nil t)
1148       (let ((flags (read (current-buffer)))
1149             (separator (read (current-buffer)))
1150             (group (read (current-buffer))))
1151         (unless (member '%NoSelect flags)
1152           (push (utf7-decode (if (stringp group)
1153                                  group
1154                                (format "%s" group)) t)
1155                 groups))))
1156     (nreverse groups)))
1157
1158 (deffoo nnimap-request-list (&optional server)
1159   (when (nnimap-possibly-change-group nil server)
1160     (with-current-buffer nntp-server-buffer
1161       (erase-buffer)
1162       (let ((groups
1163              (with-current-buffer (nnimap-buffer)
1164                (nnimap-get-groups)))
1165             sequences responses)
1166         (when groups
1167           (with-current-buffer (nnimap-buffer)
1168             (setf (nnimap-group nnimap-object) nil)
1169             (dolist (group groups)
1170               (setf (nnimap-examined nnimap-object) group)
1171               (push (list (nnimap-send-command "EXAMINE %S"
1172                                                (utf7-encode group t))
1173                           group)
1174                     sequences))
1175             (nnimap-wait-for-response (caar sequences))
1176             (setq responses
1177                   (nnimap-get-responses (mapcar #'car sequences))))
1178           (dolist (response responses)
1179             (let* ((sequence (car response))
1180                    (response (cadr response))
1181                    (group (cadr (assoc sequence sequences))))
1182               (when (and group
1183                          (equal (caar response) "OK"))
1184                 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1185                       highest exists)
1186                   (dolist (elem response)
1187                     (when (equal (cadr elem) "EXISTS")
1188                       (setq exists (string-to-number (car elem)))))
1189                   (when uidnext
1190                     (setq highest (1- (string-to-number (car uidnext)))))
1191                   (cond
1192                    ((null highest)
1193                     (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1194                    ((zerop exists)
1195                     ;; Empty group.
1196                     (insert (format "%S %d %d y\n"
1197                                     (utf7-decode group t)
1198                                     highest (1+ highest))))
1199                    (t
1200                     ;; Return the widest possible range.
1201                     (insert (format "%S %d 1 y\n" (utf7-decode group t)
1202                                     (or highest exists)))))))))
1203           t)))))
1204
1205 (deffoo nnimap-request-newgroups (date &optional server)
1206   (when (nnimap-possibly-change-group nil server)
1207     (with-current-buffer nntp-server-buffer
1208       (erase-buffer)
1209       (dolist (group (with-current-buffer (nnimap-buffer)
1210                        (nnimap-get-groups)))
1211         (unless (assoc group nnimap-current-infos)
1212           ;; Insert dummy numbers here -- they don't matter.
1213           (insert (format "%S 0 1 y\n" (utf7-encode group)))))
1214       t)))
1215
1216 (deffoo nnimap-retrieve-group-data-early (server infos)
1217   (when (and (nnimap-possibly-change-group nil server)
1218              infos)
1219     (with-current-buffer (nnimap-buffer)
1220       (erase-buffer)
1221       (setf (nnimap-group nnimap-object) nil)
1222       (setf (nnimap-initial-resync nnimap-object) 0)
1223       (let ((qresyncp (nnimap-capability "QRESYNC"))
1224             params groups sequences active uidvalidity modseq group)
1225         ;; Go through the infos and gather the data needed to know
1226         ;; what and how to request the data.
1227         (dolist (info infos)
1228           (setq params (gnus-info-params info)
1229                 group (nnimap-decode-gnus-group
1230                        (gnus-group-real-name (gnus-info-group info)))
1231                 active (cdr (assq 'active params))
1232                 uidvalidity (cdr (assq 'uidvalidity params))
1233                 modseq (cdr (assq 'modseq params)))
1234           (setf (nnimap-examined nnimap-object) group)
1235           (if (and qresyncp
1236                    uidvalidity
1237                    active
1238                    modseq)
1239               (push
1240                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1241                                           (utf7-encode group t)
1242                                           (nnimap-quirk "QRESYNC")
1243                                           uidvalidity modseq)
1244                      'qresync
1245                      nil group 'qresync)
1246                sequences)
1247             (let ((command
1248                    (if uidvalidity
1249                        "EXAMINE"
1250                      ;; If we don't have a UIDVALIDITY, then this is
1251                      ;; the first time we've seen the group, so we
1252                      ;; have to do a SELECT (which is slower than an
1253                      ;; examine), but will tell us whether the group
1254                      ;; is read-only or not.
1255                      "SELECT"))
1256                   start)
1257               (if (and active uidvalidity)
1258                   ;; Fetch the last 100 flags.
1259                   (setq start (max 1 (- (cdr active) 100)))
1260                 (setf (nnimap-initial-resync nnimap-object)
1261                       (1+ (nnimap-initial-resync nnimap-object)))
1262                 (setq start 1))
1263               (push (list (nnimap-send-command "%s %S" command
1264                                                (utf7-encode group t))
1265                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1266                           start group command)
1267                     sequences))))
1268         sequences))))
1269
1270 (defun nnimap-quirk (command)
1271   (let ((quirk (assoc command nnimap-quirks)))
1272     ;; If this server is of a type that matches a quirk, then return
1273     ;; the "quirked" command instead of the proper one.
1274     (if (or (null quirk)
1275             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1276         command
1277       (nth 2 quirk))))
1278
1279 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1280   (when (and sequences
1281              (nnimap-possibly-change-group nil server)
1282              ;; Check that the process is still alive.
1283              (get-buffer-process (nnimap-buffer))
1284              (memq (process-status (get-buffer-process (nnimap-buffer)))
1285                    '(open run)))
1286     (with-current-buffer (nnimap-buffer)
1287       ;; Wait for the final data to trickle in.
1288       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1289                                           (caar sequences)
1290                                         (cadar sequences))
1291                                       t)
1292         ;; Now we should have most of the data we need, no matter
1293         ;; whether we're QRESYNCING, fetching all the flags from
1294         ;; scratch, or just fetching the last 100 flags per group.
1295         (nnimap-update-infos (nnimap-flags-to-marks
1296                               (nnimap-parse-flags
1297                                (nreverse sequences)))
1298                              infos)
1299         ;; Finally, just return something resembling an active file in
1300         ;; the nntp buffer, so that the agent can save the info, too.
1301         (with-current-buffer nntp-server-buffer
1302           (erase-buffer)
1303           (dolist (info infos)
1304             (let* ((group (gnus-info-group info))
1305                    (active (gnus-active group)))
1306               (when active
1307                 (insert (format "%S %d %d y\n"
1308                                 (decode-coding-string
1309                                  (gnus-group-real-name group) 'utf-8)
1310                                 (cdr active)
1311                                 (car active)))))))))))
1312
1313 (defun nnimap-update-infos (flags infos)
1314   (dolist (info infos)
1315     (let* ((group (nnimap-decode-gnus-group
1316                    (gnus-group-real-name (gnus-info-group info))))
1317            (marks (cdr (assoc group flags))))
1318       (when marks
1319         (nnimap-update-info info marks)))))
1320
1321 (defun nnimap-update-info (info marks)
1322   (destructuring-bind (existing flags high low uidnext start-article
1323                                 permanent-flags uidvalidity
1324                                 vanished highestmodseq) marks
1325     (cond
1326      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1327      ;; completely empty groups.
1328      ((and (not existing)
1329            (not uidnext))
1330       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1331         (when active
1332           (gnus-set-active (gnus-info-group info) active))))
1333      ;; We have a mismatch between the old and new UIDVALIDITY
1334      ;; identifiers, so we have to re-request the group info (the next
1335      ;; time).  This virtually never happens.
1336      ((let ((old-uidvalidity
1337              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1338         (and old-uidvalidity
1339              (not (equal old-uidvalidity uidvalidity))
1340              (or (not start-article)
1341                  (> start-article 1))))
1342       (gnus-group-remove-parameter info 'uidvalidity)
1343       (gnus-group-remove-parameter info 'modseq))
1344      ;; We have the data needed to update.
1345      (t
1346       (let* ((group (gnus-info-group info))
1347              (completep (and start-article
1348                              (= start-article 1)))
1349              (active (or (gnus-active group)
1350                          (cdr (assq 'active (gnus-info-params info))))))
1351         (when uidnext
1352           (setq high (1- uidnext)))
1353         ;; First set the active ranges based on high/low.
1354         (if (or completep
1355                 (not (gnus-active group)))
1356             (gnus-set-active group
1357                              (cond
1358                               (active
1359                                (cons (min (or low (car active))
1360                                           (car active))
1361                                      (max (or high (cdr active))
1362                                           (cdr active))))
1363                               ((and low high)
1364                                (cons low high))
1365                               (uidnext
1366                                ;; No articles in this group.
1367                                (cons uidnext (1- uidnext)))
1368                               (start-article
1369                                (cons start-article (1- start-article)))
1370                               (t
1371                                ;; No articles and no uidnext.
1372                                nil)))
1373           (gnus-set-active group
1374                            (cons (car active)
1375                                  (or high (1- uidnext)))))
1376         ;; See whether this is a read-only group.
1377         (unless (eq permanent-flags 'not-scanned)
1378           (gnus-group-set-parameter
1379            info 'permanent-flags
1380            (and (or (memq '%* permanent-flags)
1381                     (memq '%Seen permanent-flags))
1382                 permanent-flags)))
1383         ;; Update marks and read articles if this isn't a
1384         ;; read-only IMAP group.
1385         (when (setq permanent-flags
1386                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1387           (if (and highestmodseq
1388                    (not start-article))
1389               ;; We've gotten the data by QRESYNCing.
1390               (nnimap-update-qresync-info
1391                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1392             ;; Do normal non-QRESYNC flag updates.
1393             ;; Update the list of read articles.
1394             (let* ((unread
1395                     (gnus-compress-sequence
1396                      (gnus-set-difference
1397                       (gnus-set-difference
1398                        existing
1399                        (cdr (assoc '%Seen flags)))
1400                       (cdr (assoc '%Flagged flags)))))
1401                    (read (gnus-range-difference
1402                           (cons start-article high) unread)))
1403               (when (> start-article 1)
1404                 (setq read
1405                       (gnus-range-nconcat
1406                        (if (> start-article 1)
1407                            (gnus-sorted-range-intersection
1408                             (cons 1 (1- start-article))
1409                             (gnus-info-read info))
1410                          (gnus-info-read info))
1411                        read)))
1412               (when (or (not (listp permanent-flags))
1413                         (memq '%Seen permanent-flags))
1414                 (gnus-info-set-read info read))
1415               ;; Update the marks.
1416               (setq marks (gnus-info-marks info))
1417               (dolist (type (cdr nnimap-mark-alist))
1418                 (when (or (not (listp permanent-flags))
1419                           (memq (car (assoc (caddr type) flags))
1420                                 permanent-flags)
1421                           (memq '%* permanent-flags))
1422                   (let ((old-marks (assoc (car type) marks))
1423                         (new-marks
1424                          (gnus-compress-sequence
1425                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1426                                    (assoc (intern (cadr type) obarray) flags)
1427                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1428                     (setq marks (delq old-marks marks))
1429                     (pop old-marks)
1430                     (when (and old-marks
1431                                (> start-article 1))
1432                       (setq old-marks (gnus-range-difference
1433                                        old-marks
1434                                        (cons start-article high)))
1435                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1436                     (when new-marks
1437                       (push (cons (car type) new-marks) marks)))))
1438               (gnus-info-set-marks info marks t))))
1439         ;; Tell Gnus whether there are any \Recent messages in any of
1440         ;; the groups.
1441         (let ((recent (cdr (assoc '%Recent flags))))
1442           (when (and active
1443                      recent
1444                      (> (car (last recent)) (cdr active)))
1445             (push (list (cons (gnus-group-real-name group) 0))
1446                   nnmail-split-history)))
1447         ;; Note the active level for the next run-through.
1448         (gnus-group-set-parameter info 'active (gnus-active group))
1449         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1450         (gnus-group-set-parameter info 'modseq highestmodseq)
1451         (nnimap-store-info info (gnus-active group)))))))
1452
1453 (defun nnimap-update-qresync-info (info existing vanished flags)
1454   ;; Add all the vanished articles to the list of read articles.
1455   (gnus-info-set-read
1456    info
1457    (gnus-add-to-range
1458     (gnus-add-to-range
1459      (gnus-range-add (gnus-info-read info)
1460                      vanished)
1461      (cdr (assq '%Flagged flags)))
1462     (cdr (assq '%Seen flags))))
1463   (let ((marks (gnus-info-marks info)))
1464     (dolist (type (cdr nnimap-mark-alist))
1465       (let ((ticks (assoc (car type) marks))
1466             (new-marks
1467              (cdr (or (assoc (caddr type) flags) ; %Flagged
1468                       (assoc (intern (cadr type) obarray) flags)
1469                       (assoc (cadr type) flags))))) ; "\Flagged"
1470         (setq marks (delq ticks marks))
1471         (pop ticks)
1472         ;; Add the new marks we got.
1473         (setq ticks (gnus-add-to-range ticks new-marks))
1474         ;; Remove the marks from messages that don't have them.
1475         (setq ticks (gnus-remove-from-range
1476                      ticks
1477                      (gnus-compress-sequence
1478                       (gnus-sorted-complement existing new-marks))))
1479         (when ticks
1480           (push (cons (car type) ticks) marks)))
1481       (gnus-info-set-marks info marks t))))
1482
1483 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1484   (if (zerop (length irange))
1485       nil
1486     (let ((result nil))
1487       (dolist (elem (split-string irange ","))
1488         (push
1489          (if (string-match ":" elem)
1490              (let ((numbers (split-string elem ":")))
1491                (cons (string-to-number (car numbers))
1492                      (string-to-number (cadr numbers))))
1493            (string-to-number elem))
1494          result))
1495       (nreverse result))))
1496
1497 (defun nnimap-store-info (info active)
1498   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1499          (entry (assoc group nnimap-current-infos)))
1500     (if entry
1501         (setcdr entry (list info active))
1502       (push (list group info active) nnimap-current-infos))))
1503
1504 (defun nnimap-flags-to-marks (groups)
1505   (let (data group totalp uidnext articles start-article mark permanent-flags
1506              uidvalidity vanished highestmodseq)
1507     (dolist (elem groups)
1508       (setq group (car elem)
1509             uidnext (nth 1 elem)
1510             start-article (nth 2 elem)
1511             permanent-flags (nth 3 elem)
1512             uidvalidity (nth 4 elem)
1513             vanished (nth 5 elem)
1514             highestmodseq (nth 6 elem)
1515             articles (nthcdr 7 elem))
1516       (let ((high (caar articles))
1517             marks low existing)
1518         (dolist (article articles)
1519           (setq low (car article))
1520           (push (car article) existing)
1521           (dolist (flag (cdr article))
1522             (setq mark (assoc flag marks))
1523             (if (not mark)
1524                 (push (list flag (car article)) marks)
1525               (setcdr mark (cons (car article) (cdr mark))))))
1526         (push (list group existing marks high low uidnext start-article
1527                     permanent-flags uidvalidity vanished highestmodseq)
1528               data)))
1529     data))
1530
1531 (defun nnimap-parse-flags (sequences)
1532   (goto-char (point-min))
1533   ;; Change \Delete etc to %Delete, so that the reader can read it.
1534   (subst-char-in-region (point-min) (point-max)
1535                         ?\\ ?% t)
1536   ;; Remove any MODSEQ entries in the buffer, because they may contain
1537   ;; numbers that are too large for 32-bit Emacsen.
1538   (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1539     (replace-match "" t t))
1540   (goto-char (point-min))
1541   (let (start end articles groups uidnext elems permanent-flags
1542               uidvalidity vanished highestmodseq)
1543     (dolist (elem sequences)
1544       (destructuring-bind (group-sequence flag-sequence totalp group command)
1545           elem
1546         (setq start (point))
1547         (when (and
1548                ;; The EXAMINE was successful.
1549                (search-forward (format "\n%d OK " group-sequence) nil t)
1550                (progn
1551                  (forward-line 1)
1552                  (setq end (point))
1553                  (goto-char start)
1554                  (setq permanent-flags
1555                        (if (equal command "SELECT")
1556                            (and (search-forward "PERMANENTFLAGS "
1557                                                 (or end (point-min)) t)
1558                                 (read (current-buffer)))
1559                          'not-scanned))
1560                  (goto-char start)
1561                  (setq uidnext
1562                        (and (search-forward "UIDNEXT "
1563                                             (or end (point-min)) t)
1564                             (read (current-buffer))))
1565                  (goto-char start)
1566                  (setq uidvalidity
1567                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1568                                                (or end (point-min)) t)
1569                             ;; Store UIDVALIDITY as a string, as it's
1570                             ;; too big for 32-bit Emacsen, usually.
1571                             (match-string 1)))
1572                  (goto-char start)
1573                  (setq vanished
1574                        (and (eq flag-sequence 'qresync)
1575                             (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1576                                                (or end (point-min)) t)
1577                             (match-string 1)))
1578                  (goto-char start)
1579                  (setq highestmodseq
1580                        (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1581                                             (or end (point-min)) t)
1582                             (match-string 1)))
1583                  (goto-char end)
1584                  (forward-line -1))
1585                ;; The UID FETCH FLAGS was successful.
1586                (or (eq flag-sequence 'qresync)
1587                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1588           (if (eq flag-sequence 'qresync)
1589               (progn
1590                 (goto-char start)
1591                 (setq start end))
1592             (setq start (point))
1593             (goto-char end))
1594           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1595             (let ((p (point)))
1596               (setq elems (read (current-buffer)))
1597               (push (cons (cadr (memq 'UID elems))
1598                           (cadr (memq 'FLAGS elems)))
1599                     articles)))
1600           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1601                              vanished highestmodseq)
1602                        articles)
1603                 groups)
1604           (goto-char end)
1605           (setq articles nil))))
1606     groups))
1607
1608 (defun nnimap-find-process-buffer (buffer)
1609   (cadr (assoc buffer nnimap-connection-alist)))
1610
1611 (deffoo nnimap-request-post (&optional server)
1612   (setq nnimap-status-string "Read-only server")
1613   nil)
1614
1615 (declare-function gnus-fetch-headers "gnus-sum"
1616                   (articles &optional limit force-new dependencies))
1617
1618 (autoload 'nnir-search-thread "nnir")
1619
1620 (deffoo nnimap-request-thread (header &optional group server)
1621   (when group
1622     (setq group (nnimap-decode-gnus-group group)))
1623   (if gnus-refer-thread-use-nnir
1624       (nnir-search-thread header)
1625     (when (nnimap-possibly-change-group group server)
1626       (let* ((cmd (nnimap-make-thread-query header))
1627              (result (with-current-buffer (nnimap-buffer)
1628                        (nnimap-command  "UID SEARCH %s" cmd))))
1629         (when result
1630           (gnus-fetch-headers
1631            (and (car result)
1632                 (delete 0 (mapcar #'string-to-number
1633                                   (cdr (assoc "SEARCH" (cdr result))))))
1634            nil t))))))
1635
1636 (defun nnimap-possibly-change-group (group server)
1637   (let ((open-result t))
1638     (when (and server
1639                (not (nnimap-server-opened server)))
1640       (setq open-result (nnimap-open-server server)))
1641     (cond
1642      ((not open-result)
1643       nil)
1644      ((not group)
1645       t)
1646      (t
1647       (with-current-buffer (nnimap-buffer)
1648         (if (equal group (nnimap-group nnimap-object))
1649             t
1650           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1651             (when (car result)
1652               (setf (nnimap-group nnimap-object) group
1653                     (nnimap-select-result nnimap-object) result)
1654               result))))))))
1655
1656 (defun nnimap-find-connection (buffer)
1657   "Find the connection delivering to BUFFER."
1658   (let ((entry (assoc buffer nnimap-connection-alist)))
1659     (when entry
1660       (if (and (buffer-name (cadr entry))
1661                (get-buffer-process (cadr entry))
1662                (memq (process-status (get-buffer-process (cadr entry)))
1663                      '(open run)))
1664           (get-buffer-process (cadr entry))
1665         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1666         nil))))
1667
1668 (defvar nnimap-sequence 0)
1669
1670 (defun nnimap-send-command (&rest args)
1671   (setf (nnimap-last-command-time nnimap-object) (current-time))
1672   (process-send-string
1673    (get-buffer-process (current-buffer))
1674    (nnimap-log-command
1675     (format "%d %s%s\n"
1676             (incf nnimap-sequence)
1677             (apply #'format args)
1678             (if (nnimap-newlinep nnimap-object)
1679                 ""
1680               "\r"))))
1681   ;; Some servers apparently can't have many outstanding
1682   ;; commands, so throttle them.
1683   (unless nnimap-streaming
1684     (nnimap-wait-for-response nnimap-sequence))
1685   nnimap-sequence)
1686
1687 (defun nnimap-log-command (command)
1688   (with-current-buffer (get-buffer-create "*imap log*")
1689     (goto-char (point-max))
1690     (insert (format-time-string "%H:%M:%S") " "
1691             (if nnimap-inhibit-logging
1692                 "(inhibited)\n"
1693               command)))
1694   command)
1695
1696 (defun nnimap-command (&rest args)
1697   (erase-buffer)
1698   (let* ((sequence (apply #'nnimap-send-command args))
1699          (response (nnimap-get-response sequence)))
1700     (if (equal (caar response) "OK")
1701         (cons t response)
1702       (nnheader-report 'nnimap "%s"
1703                        (mapconcat (lambda (a)
1704                                     (format "%s" a))
1705                                   (car response) " "))
1706       nil)))
1707
1708 (defun nnimap-get-response (sequence)
1709   (nnimap-wait-for-response sequence)
1710   (nnimap-parse-response))
1711
1712 (defun nnimap-wait-for-connection (&optional regexp)
1713   (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1714
1715 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1716   (let ((process (get-buffer-process (current-buffer))))
1717     (goto-char (point-min))
1718     (while (and (memq (process-status process)
1719                       '(open run))
1720                 (not (re-search-forward regexp nil t)))
1721       (nnheader-accept-process-output process)
1722       (goto-char (point-min)))
1723     (forward-line -1)
1724     (and (looking-at (or response-regexp regexp))
1725          (match-string 1))))
1726
1727 (defun nnimap-wait-for-response (sequence &optional messagep)
1728   (let ((process (get-buffer-process (current-buffer)))
1729         openp)
1730     (condition-case nil
1731         (progn
1732           (goto-char (point-max))
1733           (while (and (setq openp (memq (process-status process)
1734                                         '(open run)))
1735                       (progn
1736                         ;; Skip past any "*" lines that the server has
1737                         ;; output.
1738                         (while (and (not (bobp))
1739                                     (progn
1740                                       (forward-line -1)
1741                                       (looking-at "\\*"))))
1742                         (not (looking-at (format "%d .*\n" sequence)))))
1743             (when messagep
1744               (nnheader-message-maybe
1745                7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1746                nnimap-address
1747                (if (not (zerop (nnimap-initial-resync nnimap-object)))
1748                    (format " (initial sync of %d groups; please wait)"
1749                            (nnimap-initial-resync nnimap-object))
1750                  "")))
1751             (nnheader-accept-process-output process)
1752             (goto-char (point-max)))
1753           (setf (nnimap-initial-resync nnimap-object) 0)
1754           openp)
1755       (quit
1756        (when debug-on-quit
1757          (debug "Quit"))
1758        ;; The user hit C-g while we were waiting: kill the process, in case
1759        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1760        ;; NAT routers).
1761        (delete-process process)
1762        nil))))
1763
1764 (defun nnimap-parse-response ()
1765   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1766         result)
1767     (dolist (line lines)
1768       (push (cdr (nnimap-parse-line line)) result))
1769     ;; Return the OK/error code first, and then all the "continuation
1770     ;; lines" afterwards.
1771     (cons (pop result)
1772           (nreverse result))))
1773
1774 ;; Parse an IMAP response line lightly.  They look like
1775 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1776 ;; the lines into a list of strings and lists of string.
1777 (defun nnimap-parse-line (line)
1778   (let (char result)
1779     (with-temp-buffer
1780       (mm-disable-multibyte)
1781       (insert line)
1782       (goto-char (point-min))
1783       (while (not (eobp))
1784         (if (eql (setq char (following-char)) ? )
1785             (forward-char 1)
1786           (push
1787            (cond
1788             ((eql char ?\[)
1789              (split-string
1790               (buffer-substring
1791                (1+ (point))
1792                (if (search-forward "]" (line-end-position) 'move)
1793                    (1- (point))
1794                  (point)))))
1795             ((eql char ?\()
1796              (split-string
1797               (buffer-substring
1798                (1+ (point))
1799                (if (search-forward ")" (line-end-position) 'move)
1800                    (1- (point))
1801                  (point)))))
1802             ((eql char ?\")
1803              (forward-char 1)
1804              (buffer-substring
1805               (point)
1806               (1- (or (search-forward "\"" (line-end-position) 'move)
1807                       (point)))))
1808             (t
1809              (buffer-substring (point) (if (search-forward " " nil t)
1810                                            (1- (point))
1811                                          (goto-char (point-max))))))
1812            result)))
1813       (nreverse result))))
1814
1815 (defun nnimap-last-response-string ()
1816   (save-excursion
1817     (forward-line 1)
1818     (let ((end (point)))
1819       (forward-line -1)
1820       (when (not (bobp))
1821         (forward-line -1)
1822         (while (and (not (bobp))
1823                     (eql (following-char) ?*))
1824           (forward-line -1))
1825         (unless (eql (following-char) ?*)
1826           (forward-line 1)))
1827       (buffer-substring (point) end))))
1828
1829 (defun nnimap-get-responses (sequences)
1830   (let (responses)
1831     (dolist (sequence sequences)
1832       (goto-char (point-min))
1833       (when (re-search-forward (format "^%d " sequence) nil t)
1834         (push (list sequence (nnimap-parse-response))
1835               responses)))
1836     responses))
1837
1838 (defvar nnimap-incoming-split-list nil)
1839
1840 (defun nnimap-fetch-inbox (articles)
1841   (erase-buffer)
1842   (nnimap-wait-for-response
1843    (nnimap-send-command
1844     "UID FETCH %s %s"
1845     (nnimap-article-ranges articles)
1846     (format "(UID %s%s)"
1847             (format
1848              (if (nnimap-ver4-p)
1849                  "BODY.PEEK"
1850                "RFC822.PEEK"))
1851             (cond
1852              (nnimap-split-download-body-default
1853               "[]")
1854              ((nnimap-ver4-p)
1855               "[HEADER]")
1856              (t
1857               "[1]"))))
1858    t))
1859
1860 (defun nnimap-split-incoming-mail ()
1861   (with-current-buffer (nnimap-buffer)
1862     (let ((nnimap-incoming-split-list nil)
1863           (nnmail-split-methods
1864            (cond
1865             ((eq nnimap-split-methods 'default)
1866              nnmail-split-methods)
1867             (nnimap-split-methods
1868              nnimap-split-methods)
1869             (nnimap-split-fancy
1870              'nnmail-split-fancy)))
1871           (nnmail-split-fancy (or nnimap-split-fancy
1872                                   nnmail-split-fancy))
1873           (nnmail-inhibit-default-split-group t)
1874           (groups (nnimap-get-groups))
1875           new-articles)
1876       (erase-buffer)
1877       (nnimap-command "SELECT %S" nnimap-inbox)
1878       (setf (nnimap-group nnimap-object) nnimap-inbox)
1879       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1880       (when new-articles
1881         (nnimap-fetch-inbox new-articles)
1882         (nnimap-transform-split-mail)
1883         (nnheader-ms-strip-cr)
1884         (nnmail-cache-open)
1885         (nnmail-split-incoming (current-buffer)
1886                                #'nnimap-save-mail-spec
1887                                nil nil
1888                                #'nnimap-dummy-active-number
1889                                #'nnimap-save-mail-spec)
1890         (when nnimap-incoming-split-list
1891           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1892                 sequences junk-articles)
1893             ;; Create any groups that doesn't already exist on the
1894             ;; server first.
1895             (dolist (spec specs)
1896               (when (and (not (member (car spec) groups))
1897                          (not (eq (car spec) 'junk)))
1898                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1899             ;; Then copy over all the messages.
1900             (erase-buffer)
1901             (dolist (spec specs)
1902               (let ((group (car spec))
1903                     (ranges (cdr spec)))
1904                 (if (eq group 'junk)
1905                     (setq junk-articles ranges)
1906                   (push (list (nnimap-send-command
1907                                "UID COPY %s %S"
1908                                (nnimap-article-ranges ranges)
1909                                (utf7-encode group t))
1910                               ranges)
1911                         sequences))))
1912             ;; Wait for the last COPY response...
1913             (when sequences
1914               (nnimap-wait-for-response (caar sequences))
1915               ;; And then mark the successful copy actions as deleted,
1916               ;; and possibly expunge them.
1917               (nnimap-mark-and-expunge-incoming
1918                (nnimap-parse-copied-articles sequences)))
1919             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1920
1921 (defun nnimap-mark-and-expunge-incoming (range)
1922   (when range
1923     (setq range (nnimap-article-ranges range))
1924     (erase-buffer)
1925     (let ((sequence
1926            (nnimap-send-command
1927             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1928       (cond
1929        ;; If the server supports it, we now delete the message we have
1930        ;; just copied over.
1931        ((nnimap-capability "UIDPLUS")
1932         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1933        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1934        ;; user has configured it.
1935        (nnimap-expunge
1936         (setq sequence (nnimap-send-command "EXPUNGE"))))
1937       (nnimap-wait-for-response sequence))))
1938
1939 (defun nnimap-parse-copied-articles (sequences)
1940   (let (sequence copied range)
1941     (goto-char (point-min))
1942     (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
1943       (setq sequence (string-to-number (match-string 1)))
1944       (when (setq range (cadr (assq sequence sequences)))
1945         (push (gnus-uncompress-range range) copied)))
1946     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1947
1948 (defun nnimap-new-articles (flags)
1949   (let (new)
1950     (dolist (elem flags)
1951       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1952                                       (cdr elem))
1953         (push (car elem) new)))
1954     (gnus-compress-sequence (nreverse new))))
1955
1956 (defun nnimap-make-split-specs (list)
1957   (let ((specs nil)
1958         entry)
1959     (dolist (elem list)
1960       (destructuring-bind (article spec) elem
1961         (dolist (group (delete nil (mapcar #'car spec)))
1962           (unless (setq entry (assoc group specs))
1963             (push (setq entry (list group)) specs))
1964           (setcdr entry (cons article (cdr entry))))))
1965     (dolist (entry specs)
1966       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1967     specs))
1968
1969 (defun nnimap-transform-split-mail ()
1970   (goto-char (point-min))
1971   (let (article bytes)
1972     (block nil
1973       (while (not (eobp))
1974         (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
1975           (delete-region (point) (progn (forward-line 1) (point)))
1976           (when (eobp)
1977             (return)))
1978         (setq article (match-string 1)
1979               bytes (nnimap-get-length))
1980         (delete-region (line-beginning-position) (line-end-position))
1981         ;; Insert MMDF separator, and a way to remember what this
1982         ;; article UID is.
1983         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1984         (forward-char (1+ bytes))
1985         (setq bytes (nnimap-get-length))
1986         (delete-region (line-beginning-position) (line-end-position))
1987         ;; There's a body; skip past that.
1988         (when bytes
1989           (forward-char (1+ bytes))
1990           (delete-region (line-beginning-position) (line-end-position)))))))
1991
1992 (defun nnimap-dummy-active-number (group &optional server)
1993   1)
1994
1995 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1996   (let (article)
1997     (goto-char (point-min))
1998     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1999         (error "Invalid nnimap mail")
2000       (setq article (string-to-number (match-string 1))))
2001     (push (list article
2002                 (if (eq group-art 'junk)
2003                     (list (cons 'junk 1))
2004                   group-art))
2005           nnimap-incoming-split-list)))
2006
2007 (defun nnimap-make-thread-query (header)
2008   (let* ((id  (mail-header-id header))
2009          (refs (split-string
2010                 (or (mail-header-references header)
2011                     "")))
2012          (value
2013           (format
2014            "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2015            id id)))
2016     (dolist (refid refs value)
2017       (setq value (format
2018                    "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2019                    refid refid value)))))
2020
2021
2022 (provide 'nnimap)
2023
2024 ;;; nnimap.el ends here