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