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